.NET core3.1使用cookie进行身份认证

一个系统,用户身份认证少不了,ASP.NET Core提供完整的解决方案Identity,用户建立和维护登陆名;也提供能cookie和JwtBearer认证方案,固然你可使用第三方认证Oauth、openId。项目没有采用先后端分离,是一个标准的mvc项目,因此本文采用系统提供的cookie认证 记录一下简单认证流程,(1)使用用户帐号密码进行登陆,验证合法登陆(2)确认合法身份以后,会颁发一个认证票据(加密)会携带与该用户相关的身份、权限以及其余信息。(3)退出。ajax

主要会使用Microsoft.AspNetCore.Authentication.Abstractions包中 AuthenticationHttpContextExtensions类,它是基于HttpContext上公开身认证的扩展法:后端

方法 描述
SignInAsync 登陆用户.用户登陆成功后颁发一个证书(加密的用户凭证,这个凭证放入Cookie中),用来标识用户的身份
SignOutAsync 注销退出.清除Cookie
GetTokenAsync 用来获取 AuthenticationProperties 中保存的额外信息
ForbidAsync 通知用户权限不足,若是是ajax请求返回403状态码,不是ajax请求跳转指定的url
ChallengeAsync 通知用户须要登陆。在默认实现类AuthenticationHandler中,返回401
AuthenticateAsync 验证在 SignInAsync 中颁发的证书,并返回一个 AuthenticateResult 对象,表示用户的身份。

登陆建立一个cookie认证

这里涉及几个对象:Claim声明经常表明,认证用户身份的元数据信息,好比手机号、邮箱、用户名等等。ClaimsIdentity声明主体,表明一个认证用户的身份证,固然包含声明的集合。ClaimsPrincipal身份证持有者。微信

流程:建立一个包含用户信息的 cookie须要构造一个ClaimsPrincipal。将序列化用户信息并将其存储在中 cookie 。cookie

用必要的 Claim来构造一个ClaimsIdentity,而后调用 SignInAsync 来登陆用户。session

public async Task<Result> UserLogin([FromForm] UserLoginInput input)
{
//登陆逻辑
var model = userService.UserLogin(input);

//1.建立cookie 保存用户信息,使用claim。将序列化用户信息并将其存储在cookie
var claims = new List<Claim>()
{
new Claim(ClaimTypes.MobilePhone,model.Mobile),
new Claim(ClaimTypes.Name,model.UserName),
new Claim("Id",model.SysNo.ToString())
};

//2.建立声明主题 指定认证方式 这里使用cookie
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

//3.配置认证属性 好比过时时间,是否持久化。。。。
var authProperties = new AuthenticationProperties
{
//AllowRefresh = <bool>,
// Refreshing the authentication session should be allowed.

//ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
// The time at which the authentication ticket expires. A
// value set here overrides the ExpireTimeSpan option of
// CookieAuthenticationOptions set with AddCookie.

//IsPersistent = true,
//持久化 ,好比 登陆的时候 勾选记住我 复选框

//IssuedUtc = <DateTimeOffset>,
//绝对cookie过时

//RedirectUri = <string>
// The full path or absolute URI to be used as an http
// redirect response value.
};

//4.登陆
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);

return Result.ResponseSuccess();
}

SignInAsync 建立一个加密的 cookie ,并将其添加到当前响应中。mvc

退出

退出很简单,主要用户清除cookieapp

HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

获取认证信息

登陆以后,咱们一般会获取一些声明中的信息,可使用 HttpContext.User 将会返回一个ClaimsPrincipal对象前后端分离

ClaimsPrincipal principal = HttpContext.User;
if (null != principal)
{
foreach (Claim claim in principal.Claims)
{
var ii = "CLAIM TYPE: " + claim.Type + "; CLAIM VALUE: " + claim.Value + "</br>";
}

}

统一处理获取到的信息,赋值UserViewModel实例CurrentLoginUserasync

public class BaseController : Controller
{
public UserViewModel CurrentLoginUser
{
get
{
var principal = HttpContext.User;
if (principal != null)
{
return new UserViewModel()
{
UserName = principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value,
Mobile = principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.MobilePhone)?.Value,
SysNo = new Guid(principal.Claims.FirstOrDefault(x => x.Type == "Id")?.Value ?? Guid.Empty.ToString())
};
}
return null;
}
}

使用ide

 var userId = CurrentLoginUser.SysNo;

startup类配置

在ConfigureServices方法添加

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath =new PathString("/User/Login");

});

在Configure方法添加

application.UseAuthentication();
application.UseAuthorization();

参考:

https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/cookie?view=aspnetcore-3.1

本文分享自微信公众号 - dotNET知音(AAshiyou)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。

相关文章
相关标签/搜索