Asp.Net Core添加請(qǐng)求頭自定義認(rèn)證的示例
前言
小項(xiàng)目中需要添加 Api 請(qǐng)求權(quán)限認(rèn)證, 并且只是專用網(wǎng)絡(luò)內(nèi)使用,于是只想簡(jiǎn)單得認(rèn)證下是否可以訪問(wèn), 順便也是一種學(xué)習(xí)的過(guò)程,簡(jiǎn)單記錄一下
要點(diǎn)
實(shí)現(xiàn) IAuthenticationHandler 接口:4 個(gè)方法
- 首先會(huì)調(diào)用 InitializeAsync 獲取到 scheme 和 context
- 然后調(diào)用 AuthenticateAsync ,在這里獲取 context 中的 Header 中需要傳過(guò)來(lái)的驗(yàn)證信息,然后進(jìn)行相關(guān)驗(yàn)證,根據(jù)不同的結(jié)果會(huì)分別調(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)已過(guò)期。"));
}
// 生成 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;
}
}
GuidToken 類就是我們自定義的 token 管理器
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) {
// 注冊(cè)使用
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添加請(qǐng)求頭自定義認(rèn)證的示例的詳細(xì)內(nèi)容,更多關(guān)于Asp.Net Core添加請(qǐng)求頭認(rèn)證的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- ASP.NET Core3.1 Ocelot認(rèn)證的實(shí)現(xiàn)
- ASP.NET Core使用JWT認(rèn)證授權(quán)的方法
- 深入解讀ASP.NET Core身份認(rèn)證過(guò)程實(shí)現(xiàn)
- ASP.NET Core 實(shí)現(xiàn)基本認(rèn)證的示例代碼
- ASP.NET Core學(xué)習(xí)之使用JWT認(rèn)證授權(quán)詳解
- ASP.NET Core Authentication認(rèn)證實(shí)現(xiàn)方法
- Asp.net Core中實(shí)現(xiàn)自定義身份認(rèn)證的示例代碼
- 淺談ASP.NET Core 中jwt授權(quán)認(rèn)證的流程原理
- ASP.Net Core3.0中使用JWT認(rèn)證的實(shí)現(xiàn)
- Asp.Net Core基于JWT認(rèn)證的數(shù)據(jù)接口網(wǎng)關(guān)實(shí)例代碼
- ASP.NET學(xué)習(xí)CORE中使用Cookie身份認(rèn)證方法
相關(guān)文章
Asp.net+jquery+.ashx文件實(shí)現(xiàn)分頁(yè)思路
分頁(yè)思路: .ashx程序中,編寫好取得不同頁(yè)碼的程序。在頁(yè)面布局好的前提下,留下數(shù)據(jù)區(qū)域 div。然后在頁(yè)面請(qǐng)求 .ashx程序生成下一頁(yè)的html代碼。覆蓋div.innerHTMl2013-03-03
.NET+JS對(duì)用戶輸入內(nèi)容進(jìn)行字?jǐn)?shù)提示功能的實(shí)例代碼
.NET+JS對(duì)用戶輸入內(nèi)容進(jìn)行字?jǐn)?shù)提示功能的實(shí)例代碼,需要的朋友可以參考一下2013-06-06
asp.net core實(shí)現(xiàn)在線生成多個(gè)文件將多個(gè)文件打包為zip返回的操作
遇到安卓手機(jī)解壓縮文件損壞問(wèn)題時(shí),可以考慮兩種解決方案,方案一是使用SharpCompress庫(kù),它是一個(gè)開源項(xiàng)目,能夠提供強(qiáng)大的壓縮與解壓功能,支持多種文件格式,方案二是采用aspose.zip庫(kù),這兩種方法都能有效解決文件損壞的問(wèn)題2024-11-11
.NET6創(chuàng)建Windows服務(wù)的實(shí)現(xiàn)步驟
本文主要介紹了.NET6創(chuàng)建Windows服務(wù)的實(shí)現(xiàn)步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
ASP.NET 緩存分析和實(shí)踐淺析提高運(yùn)行效率
說(shuō)到ASP.NET緩存,那就是:盡早緩存;經(jīng)常緩存您應(yīng)該在應(yīng)用程序的每一層都實(shí)現(xiàn)緩存。2010-02-02
在.NET Core中用最原生的方式讀取Nacos的配置方法(推薦)
這篇文章主要介紹了在.NET Core中用最原生的方式讀取Nacos的配置方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04

