ASP.NET Core 授权二(自定义token)

发布时间 2024-01-02 15:57:02作者: leafroc

TokenAuthenticationHandler.cs

首先自定义一个类TokenAuthenticationHandler,然后需要继承IAuthenticationHandler接口
具体代码:

public class TokenAuthenticationHandler : IAuthenticationHandler
{
    private AuthenticationScheme _scheme;
    private HttpContext _context;
    /// <summary>
    /// 鉴权初始化
    /// </summary>
    /// <param name="scheme">鉴权架构名称</param>
    /// <param name="context">HttpContext</param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
    {
        _scheme = scheme;
        _context = context;
        return Task.CompletedTask;
    }
    public Task<AuthenticateResult> AuthenticateAsync()
    {
        string token = _context.Request.Headers["Authorization"];
        if (token == "test")
        {
            ClaimsIdentity identity = new ClaimsIdentity("Ctm");
            identity.AddClaims(new List<Claim>(){
                new Claim(ClaimTypes.Name,"admin"),
                new Claim(ClaimTypes.NameIdentifier,"1")
            });
            var claimsPrincipal = new ClaimsPrincipal(identity);
            return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(claimsPrincipal, null, _scheme.Name)));
        }
        return Task.FromResult(AuthenticateResult.Fail("token错误,请重新登录"));
    }

    /// <summary>
    /// 未登录
    /// </summary>
    /// <param name="properties"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public Task ChallengeAsync(AuthenticationProperties? properties)
    {
        _context.Response.Redirect("/api/Login/NoLogin");
        return Task.CompletedTask;
    }

    /// <summary>
    /// 没有权限访问
    /// </summary>
    /// <param name="properties"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public Task ForbidAsync(AuthenticationProperties? properties)
    {
        _context.Response.StatusCode = 403;
        return Task.CompletedTask;
    }
}

Program.cs

#region  自定义Token验证
builder.Services.AddAuthentication(option => 
{
    //把自定义的鉴权方案添加到鉴权架构中
    option.AddScheme<TokenAuthenticationHandler>("token","myToken");
    option.DefaultAuthenticateScheme = "token";
    option.DefaultChallengeScheme = "token";
    option.DefaultForbidScheme = "token";
});
#endregion

请求

后续需要鉴权的接口,在请求上都需要加上Authorization参数

重要类型

Claim:相当于一个身份单元,存储着键值信息

ClaimsIdentity:身份证,身份单元的集合(可以理解为身份证上有多个身份单元)

ClaimsPrincipal:身份证的载体,一个人有多重身份,那么会有多个身份证,比如既有身份证又有学生证

AuthenticateResult:认证结果

AuthenticationTicket:表示一个经过认证后颁发的证书