您好,登錄后才能下訂單哦!
小編給大家分享一下Asp.Net Core如何添加請求頭自定義認(rèn)證,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
實(shí)現(xiàn) IAuthenticationHandler 接口:4 個(gè)方法
首先會調(diào)用 InitializeAsync 獲取到 scheme 和 context
然后調(diào)用 AuthenticateAsync ,在這里獲取 context 中的 Header 中需要傳過來的驗(yàn)證信息,然后進(jìn)行相關(guān)驗(yàn)證,根據(jù)不同的結(jié)果會分別調(diào)用 ChallengeAsync 或者 ForbidAsync
public class HeaderAuth : IAuthenticationHandler { public AuthenticationScheme Scheme { get; private set; } public HttpContext CurrentContext { get; private set; } public Task<AuthenticateResult> AuthenticateAsync() { var token = CurrentContext.Request.Headers[GuidToken.GUID_TOKEN_KEY].ToString(); var (isValid, tokenEntity) = GuidToken.Valid(token); if (!isValid || tokenEntity == null) { return Task.FromResult(AuthenticateResult.Fail("未登錄或授權(quán)已過期。")); } // 生成 AuthenticationTicket AuthenticationTicket ticket = new AuthenticationTicket(tokenEntity.ToClaimsPrincipal(), Scheme.Name); return Task.FromResult(AuthenticateResult.Success(ticket)); } public Task ChallengeAsync(AuthenticationProperties properties) { CurrentContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return Task.CompletedTask; } public Task ForbidAsync(AuthenticationProperties properties) { CurrentContext.Response.StatusCode = (int)HttpStatusCode.Forbidden; return Task.CompletedTask; } public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context) { Scheme = scheme; CurrentContext = context; return Task.CompletedTask; } }
public class GuidToken { public const string GUID_TOKEN_NAME = "MtGuidTokenAuthentication"; public const string DEFAULT_AUTHENTICATION_TYPE = "local"; public const int TOKEN_LENGTH = 32; public const string GUEST = "GUEST"; public const string DEFAULT_ROLE = "USER"; public const string DEFAULT_OPENID = "DEFAULT_OPENID"; public const string GUID_TOKEN_KEY = "Token"; private static int expireDuration = 0; public string OpenId { get; set; } public string Role { get; set; } public DateTime Expire { get; set; } private static readonly Dictionary<string, GuidToken> tokenCache = new Dictionary<string, GuidToken>(); public static (bool, GuidToken) Valid(string token) { if (string.IsNullOrEmpty(token) || token.Length != TOKEN_LENGTH) { return (false, null); } // 從 Session 中獲取令牌實(shí)體 GuidToken tokenEntity = GetTokenCache(); if (tokenEntity == null) { return (false, null); } else { tokenEntity.Expire = DateTime.Now.AddMinutes(expireDuration); } return (true, tokenEntity); GuidToken GetTokenCache() { if (tokenCache.TryGetValue(token, out var val)) { if (val.Expire > DateTime.Now) return val; else tokenCache.Remove(token); } return null; } } public static string Create(string openId = DEFAULT_OPENID, string role = DEFAULT_ROLE, int minutes = 30) { var token = Guid.NewGuid().ToString("N"); expireDuration = minutes; var entity = new GuidToken { OpenId = openId, Role = role, Expire = DateTime.Now.AddMinutes(expireDuration) }; tokenCache.Add(token, entity); return token; } /// <summary> /// 令牌實(shí)體 轉(zhuǎn) ClaimsPrincipal /// </summary> /// <param name="token"></param> /// <returns></returns> public ClaimsPrincipal ToClaimsPrincipal() { var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, OpenId), new Claim(ClaimTypes.Role, Role), }, GuidToken.DEFAULT_AUTHENTICATION_TYPE); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); return claimsPrincipal; } }
在 Startup 中配置
public void ConfigureServices(IServiceCollection services) { // 注冊使用 services.AddAuthentication(options => { options.AddScheme<HeaderAuth>(GuidToken.GUID_TOKEN_NAME, "Default Guid Token"); options.DefaultAuthenticateScheme = GuidToken.GUID_TOKEN_NAME; options.DefaultChallengeScheme = GuidToken.GUID_TOKEN_NAME; }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("any"); app.UseStaticFiles(); // 開啟認(rèn)證 app.UseAuthentication(); app.UseRouting(); // 開啟授權(quán) app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
在控制器中使用標(biāo)簽
[Authorize] public class JobController : ControllerBase {}
看完了這篇文章,相信你對“Asp.Net Core如何添加請求頭自定義認(rèn)證”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。