using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Wms.Tools; namespace Wms.Filter { /// /// MyAuthHandler /// public class MyAuthHandler : IAuthenticationHandler { private ITokenHelper tokenHelper; public MyAuthHandler(ITokenHelper _tokenHelper) //通过依赖注入得到数据访问层实例 { tokenHelper = _tokenHelper; } /// /// /// public const string SchemeName = "MyAuth"; AuthenticationScheme _scheme; HttpContext _context; /// /// 初始化认证 /// public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context) { _scheme = scheme; _context = context; return Task.CompletedTask; } /// /// 认证处理 /// public Task AuthenticateAsync() { var req = _context.Request.Headers; var isLogin = req["token"].FirstOrDefault(); if (isLogin == null) { return Task.FromResult(AuthenticateResult.Fail("未登陆")); } string userId = ""; string userName = ""; TokenType tokenType = tokenHelper.ValiTokenState(isLogin, a => a["iss"] == "WYY" && a["aud"] == "EveryTestOne", action => { userId = action["loginID"]; userName = action["LoginName"]; }); if (tokenType == TokenType.Fail) { return Task.FromResult(AuthenticateResult.Fail("验证失败")); } if (tokenType == TokenType.Expired) { return Task.FromResult(AuthenticateResult.Fail("token值过期")); } //_context.ActionArguments.Add("userId", Convert.ToInt32(userId)); var ticket = GetAuthTicket(userId, userName); var data = AuthenticateResult.Success(ticket); return Task.FromResult(data); } AuthenticationTicket GetAuthTicket(string name, string role) { var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, name), new Claim(ClaimTypes.NameIdentifier, role), }, "My_Auth"); var principal = new ClaimsPrincipal(claimsIdentity); return new AuthenticationTicket(principal, _scheme.Name); } /// /// 权限不足时的处理 /// public Task ForbidAsync(AuthenticationProperties properties) { _context.Response.StatusCode = (int)HttpStatusCode.Forbidden; return Task.CompletedTask; } /// /// 未登录时的处理 /// public Task ChallengeAsync(AuthenticationProperties properties) { _context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return Task.CompletedTask; } } }