.Net Core中自定义认证实现

 最近项目中需要对项目同时支持JWT认证,以及自定义的认证校验方式认证。通过对官方文档了解,得到认证实现主要通过继承 IAuthenticationHandler 或 AuthenticationHandler<TOptions>来实现自定义认证的处理。 

 那么接下来实现一个自定义的认证访问。

二、自定义认证实现 

 1、根据前面内容得知,处理认证通过IAuthenticationHandler 实例处理;那么首先添加一个自定义IAuthenticationHandler 类型:

/// <summary> /// 方式一:自定义认证处理器 /// </summary> public class CustomerAuthenticationHandler : IAuthenticationHandler { private IUserService _userService; public CustomerAuthenticationHandler(IUserService userService) { _userService = userService; } /// <summary> /// 自定义认证Scheme名称 /// </summary> public const string CustomerSchemeName = "cusAuth"; private AuthenticationScheme _scheme; private HttpContext _context; /// <summary> /// 认证逻辑:认证校验主要逻辑 /// </summary> /// <returns></returns> public Task<AuthenticateResult> AuthenticateAsync() { AuthenticateResult result; _context.Request.Headers.TryGetValue("Authorization", out StringValues values); string valStr = values.ToString(); if (!string.IsNullOrWhiteSpace(valStr)) { //认证模拟basic认证:cusAuth YWRtaW46YWRtaW4= string[] authVal = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(valStr.Substring(CustomerSchemeName.Length + 1))).Split(':'); var loginInfo = new Dto.LoginDto() { Username = authVal[0], Password = authVal[1] }; var validVale = _userService.IsValid(loginInfo); if (!validVale) result = AuthenticateResult.Fail("未登陆"); else { var ticket = GetAuthTicket(loginInfo.Username, "admin"); result = AuthenticateResult.Success(ticket); } } else { result = AuthenticateResult.Fail("未登陆"); } return Task.FromResult(result); } /// <summary> /// 未登录时的处理 /// </summary> /// <param></param> /// <returns></returns> public Task ChallengeAsync(AuthenticationProperties properties) { _context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return Task.CompletedTask; } /// <summary> /// 权限不足时处理 /// </summary> /// <param></param> /// <returns></returns> public Task ForbidAsync(AuthenticationProperties properties) { _context.Response.StatusCode = (int)HttpStatusCode.Forbidden; return Task.CompletedTask; } /// <summary> /// 初始化认证 /// </summary> /// <param></param> /// <param></param> /// <returns></returns> public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context) { _scheme = scheme; _context = context; return Task.CompletedTask; } #region 认证校验逻辑 /// <summary> /// 生成认证票据 /// </summary> /// <param></param> /// <param></param> /// <returns></returns> private AuthenticationTicket GetAuthTicket(string name, string role) { var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, name), new Claim(ClaimTypes.Role, role), }, CustomerSchemeName); var principal = new ClaimsPrincipal(claimsIdentity); return new AuthenticationTicket(principal, _scheme.Name); } #endregion } /// <summary> /// 方式二:继承已实现的基类 /// </summary> public class SubAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions> { public SubAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { } protected override Task<AuthenticateResult> HandleAuthenticateAsync() { throw new NotImplementedException(); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwxxww.html