TokenAuthenticationHandler.cs
首先自定義一個(gè)類TokenAuthenticationHandler,然后需要繼承IAuthenticationHandler接口
具體代碼:
public class TokenAuthenticationHandler : IAuthenticationHandler
{
private AuthenticationScheme _scheme;
private HttpContext _context;
/// <summary>
/// 鑒權(quán)初始化
/// </summary>
/// <param name="scheme">鑒權(quán)架構(gòu)名稱</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錯(cuò)誤,請重新登錄"));
}
/// <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>
/// 沒有權(quán)限訪問
/// </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驗(yàn)證
builder.Services.AddAuthentication(option =>
{
//把自定義的鑒權(quán)方案添加到鑒權(quán)架構(gòu)中
option.AddScheme<TokenAuthenticationHandler>("token","myToken");
option.DefaultAuthenticateScheme = "token";
option.DefaultChallengeScheme = "token";
option.DefaultForbidScheme = "token";
});
#endregion
請求
后續(xù)需要鑒權(quán)的接口,在請求上都需要加上Authorization參數(shù)
重要類型
Claim:相當(dāng)于一個(gè)身份單元,存儲(chǔ)著鍵值信息
ClaimsIdentity:身份證,身份單元的集合(可以理解為身份證上有多個(gè)身份單元)
ClaimsPrincipal:身份證的載體,一個(gè)人有多重身份,那么會(huì)有多個(gè)身份證,比如既有身份證又有學(xué)生證
AuthenticateResult:認(rèn)證結(jié)果文章來源:http://www.zghlxwxcb.cn/news/detail-773888.html
AuthenticationTicket:表示一個(gè)經(jīng)過認(rèn)證后頒發(fā)的證書文章來源地址http://www.zghlxwxcb.cn/news/detail-773888.html
到了這里,關(guān)于ASP.NET Core 鑒權(quán)授權(quán)二(自定義token)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!