如何在ASP.NET Core中实现一个基础的身份认证

  • 时间:2018-12-28 22:53 作者:哈喽程序猿 来源:哈喽程序猿 阅读:812
  • 扫一扫,手机访问
摘要:注:本文提到的代码示例下载地址> How to achieve a basic authorization in ASP.NET Core如何在ASP.NET Core中实现一个基础的身份认证ASP.NET终于可以跨平台了,但是不是我们常用的ASP.NET, 而是叫一个ASP.NET Core的新平

注:本文提到的代码示例下载地址> How to achieve a basic authorization in ASP.NET Core

如何在ASP.NET Core中实现一个基础的身份认证

ASP.NET终于可以跨平台了,但是不是我们常用的ASP.NET, 而是叫一个ASP.NET Core的新平台,他可以跨Windows, Linux, OS X等平台来部署你的web应用程序,你可以了解为,这个框架就是ASP.NET的下一个版本,相对于传统ASP.NET程序,它还是有少量不同的地方的,比方很多类库在这两个平台之间是不通用的。

今天首先我们在ASP.NET Core中来实现一个基础的身份认证,既登陆功能。

前期准备:

1.推荐使用 VS 2015 Update3 作为你的IDE,下载地址:www.visualstudio.com

2.你需要安装.NET Core的运行环境以及开发工具,这里提供VS版:www.microsoft.com/net/core

创立项目:

在VS中新建项目,项目类型选择ASP.NET Core Web Application (.NET Core), 输入项目名称为TestBasicAuthor。

如何在ASP.NET Core中实现一个基础的身份认证

接下来选择 Web Application, 右侧身份认证选择:No Authentication

如何在ASP.NET Core中实现一个基础的身份认证

打开Startup.cs

在ConfigureServices方法中加入如下代码:

services.AddAuthorization();

在Configure方法中加入如下代码:

如何在ASP.NET Core中实现一个基础的身份认证

app.UseCookieAuthentication(new CookieAuthenticationOptions

{

AuthenticationScheme = "Cookie",

LoginPath = new PathString("/Account/Login"),

AccessDeniedPath = new PathString("/Account/Forbidden"),

AutomaticAuthenticate = true,

AutomaticChallenge = true });

如何在ASP.NET Core中实现一个基础的身份认证

完整的代码应该是这样:

如何在ASP.NET Core中实现一个基础的身份认证

public void ConfigureServices(IServiceCollection services)

{

services.AddMvc();

services.AddAuthorization();

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

{

app.UseCookieAuthentication(new CookieAuthenticationOptions

{

AuthenticationScheme = "Cookie",

LoginPath = new PathString("/Account/Login"),

AccessDeniedPath = new PathString("/Account/Forbidden"),

AutomaticAuthenticate = true,

AutomaticChallenge = true

});

app.UseMvc(routes =>

{

routes.MapRoute(

name: "default",

template: "{controller=Home}/{action=Index}/{id?}");

});

}

如何在ASP.NET Core中实现一个基础的身份认证

你或者许会发现贴进去的代码是报错的,这是由于还没有引入对应的包,进入报错的这一行,点击灯泡,加载对应的包即可以了。

如何在ASP.NET Core中实现一个基础的身份认证

在项目下创立一个文件夹命名为Model,并向里面增加一个类User.cs

代码应该是这样

public class User

{

public string UserName { get; set; }

public string Password { get; set; }

}

创立一个控制器,取名为:AccountController.cs

在类中贴入如下代码:

如何在ASP.NET Core中实现一个基础的身份认证

[HttpGet]

public IActionResult Login()

{

return View();

}

[HttpPost]

public async Task Login(User userFromFore)

{

var userFromStorage = TestUserStorage.UserList

.FirstOrDefault(m => m.UserName == userFromFore.UserName && m.Password == userFromFore.Password);

if (userFromStorage != null)

{

//you can add all of ClaimTypes in this collection

var claims = new List()

{

new Claim(ClaimTypes.Name,userFromStorage.UserName)

//,new Claim(ClaimTypes.Email,"emailaccount@microsoft.com")

};

//init the identity instances

var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin"));

//signin

await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties

{

ExpiresUtc = DateTime.UtcNow.AddMinutes(20),

IsPersistent = false,

AllowRefresh = false

});

return RedirectToAction("Index", "Home");

}

else

{

ViewBag.ErrMsg = "UserName or Password is invalid";

return View();

}

}

public async Task Logout()

{

await HttpContext.Authentication.SignOutAsync("Cookie");

return RedirectToAction("Index", "Home");

}

如何在ASP.NET Core中实现一个基础的身份认证

相同的文件里让我们来增加一个模拟客户存储的类

如何在ASP.NET Core中实现一个基础的身份认证

//for simple, I'm not using the database to store the user data, just using a static class to replace it.

public static class TestUserStorage

{

public static List UserList { get; set; } = new List() {

new User { UserName = "User1",Password = "112233"}

};

}

如何在ASP.NET Core中实现一个基础的身份认证

接下来修复好各种引用错误。

完整的代码应该是这样

如何在ASP.NET Core中实现一个基础的身份认证

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Mvc;

using TestBasicAuthor.Model;

using System.Security.Claims;

using Microsoft.AspNetCore.Http.Authentication;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace TestBasicAuthor.Controllers

{

public class AccountController : Controller

{

[HttpGet]

public IActionResult Login()

{

return View();

}

[HttpPost]

public async Task Login(User userFromFore)

{

var userFromStorage = TestUserStorage.UserList

.FirstOrDefault(m => m.UserName == userFromFore.UserName && m.Password == userFromFore.Password);

if (userFromStorage != null)

{

//you can add all of ClaimTypes in this collection

var claims = new List()

{

new Claim(ClaimTypes.Name,userFromStorage.UserName)

//,new Claim(ClaimTypes.Email,"emailaccount@microsoft.com")

};

//init the identity instances

var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin"));

//signin

await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties

{

ExpiresUtc = DateTime.UtcNow.AddMinutes(20),

IsPersistent = false,

AllowRefresh = false

});

return RedirectToAction("Index", "Home");

}

else

{

ViewBag.ErrMsg = "UserName or Password is invalid";

return View();

}

}

public async Task Logout()

{

await HttpContext.Authentication.SignOutAsync("Cookie");

return RedirectToAction("Index", "Home");

}

}

//for simple, I'm not using the database to store the user data, just using a static class to replace it.

public static class TestUserStorage

{

public static List UserList { get; set; } = new List() {

new User { UserName = "User1",Password = "112233"}

};

}

}

如何在ASP.NET Core中实现一个基础的身份认证

在Views文件夹中创立一个Account文件夹,在Account文件夹中创立一个名位index.cshtml的View文件。

贴入如下代码:

如何在ASP.NET Core中实现一个基础的身份认证

@model TestBasicAuthor.Model.User

@using (Html.BeginForm())

{

@ViewBag.ErrMsg
UserName@Html.TextBoxFor(m => m.UserName)
Password@Html.PasswordFor(m => m.Password)

}

如何在ASP.NET Core中实现一个基础的身份认证

打开HomeController.cs

增加一个Action, AuthPage.

如何在ASP.NET Core中实现一个基础的身份认证

[Authorize]

[HttpGet]

public IActionResult AuthPage()

{

return View();

}

如何在ASP.NET Core中实现一个基础的身份认证

在Views/Home下增加一个视图,名为AuthPage.cshtml

如何在ASP.NET Core中实现一个基础的身份认证

Auth page

if you are not authorized, you can't visit this page.

如何在ASP.NET Core中实现一个基础的身份认证

到此,一个基础的身份认证就完成了,核心登陆方法如下:

如何在ASP.NET Core中实现一个基础的身份认证

await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties

{

ExpiresUtc = DateTime.UtcNow.AddMinutes(20),

IsPersistent = false,

AllowRefresh = false});

如何在ASP.NET Core中实现一个基础的身份认证

启用验证如下:

如何在ASP.NET Core中实现一个基础的身份认证

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

{

app.UseCookieAuthentication(new CookieAuthenticationOptions

{

AuthenticationScheme = "Cookie",

LoginPath = new PathString("/Account/Login"),

AccessDeniedPath = new PathString("/Account/Forbidden"),

AutomaticAuthenticate = true,

AutomaticChallenge = true

});}

如何在ASP.NET Core中实现一个基础的身份认证

在某个Controller或者Action增加[Author],就可配置位需要登陆验证的页面。

最后:如何运行这个Sample以及下载完整的代码请访问:How to achieve a basic authorization in ASP.NET Core

更多脚本样例, 访问微软One Code样例库:http://aka.ms/onescriptsamples 更多代码样例, 访问微软One Script样例库:http://aka.ms/onecodesamples

  • 全部评论(0)
最新发布的资讯信息
【系统环境|】2FA验证器 验证码如何登录(2024-04-01 20:18)
【系统环境|】怎么做才能建设好外贸网站?(2023-12-20 10:05)
【系统环境|数据库】 潮玩宇宙游戏道具收集方法(2023-12-12 16:13)
【系统环境|】遥遥领先!青否数字人直播系统5.0发布,支持真人接管实时驱动!(2023-10-12 17:31)
【系统环境|服务器应用】克隆自己的数字人形象需要几步?(2023-09-20 17:13)
【系统环境|】Tiktok登录教程(2023-02-13 14:17)
【系统环境|】ZORRO佐罗软件安装教程及一键新机使用方法详细简介(2023-02-10 21:56)
【系统环境|】阿里云 centos 云盘扩容命令(2023-01-10 16:35)
【系统环境|】补单系统搭建补单源码搭建(2022-05-18 11:35)
【系统环境|服务器应用】高端显卡再度登上热搜,竟然是因为“断崖式”的降价(2022-04-12 19:47)
手机二维码手机访问领取大礼包
返回顶部