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:认证结果文章来源:https://www.toymoban.com/news/detail-772113.html
AuthenticationTicket:表示一个经过认证后颁发的证书文章来源地址https://www.toymoban.com/news/detail-772113.html
到了这里,关于ASP.NET Core 授权二(自定义token)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!