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
|
{
|
/// <summary>
|
/// MyAuthHandler
|
/// </summary>
|
public class MyAuthHandler : IAuthenticationHandler
|
{
|
private ITokenHelper tokenHelper;
|
public MyAuthHandler(ITokenHelper _tokenHelper) //通过依赖注入得到数据访问层实例
|
{
|
tokenHelper = _tokenHelper;
|
}
|
/// <summary>
|
///
|
/// </summary>
|
public const string SchemeName = "MyAuth";
|
|
AuthenticationScheme _scheme;
|
HttpContext _context;
|
|
/// <summary>
|
/// 初始化认证
|
/// </summary>
|
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
|
{
|
_scheme = scheme;
|
_context = context;
|
return Task.CompletedTask;
|
}
|
|
/// <summary>
|
/// 认证处理
|
/// </summary>
|
public Task<AuthenticateResult> AuthenticateAsync()
|
{
|
var req = _context.Request.Headers;
|
var isLogin = req["token"].FirstOrDefault();
|
if (isLogin == null)
|
{
|
return Task.FromResult(AuthenticateResult.Fail("未登陆"));
|
}
|
|
string userId = "";
|
TokenType tokenType = tokenHelper.ValiTokenState(isLogin, a => a["iss"] == "WYY" && a["aud"] == "EveryTestOne", action => { userId = action["loginID"]; });
|
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, userId);
|
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.Role, role),
|
}, "My_Auth");
|
|
var principal = new ClaimsPrincipal(claimsIdentity);
|
return new AuthenticationTicket(principal, _scheme.Name);
|
}
|
|
/// <summary>
|
/// 权限不足时的处理
|
/// </summary>
|
public Task ForbidAsync(AuthenticationProperties properties)
|
{
|
_context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
|
return Task.CompletedTask;
|
}
|
|
/// <summary>
|
/// 未登录时的处理
|
/// </summary>
|
public Task ChallengeAsync(AuthenticationProperties properties)
|
{
|
_context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
|
return Task.CompletedTask;
|
}
|
}
|
}
|