[英]How to modify default local JWT authentication in dot net core
我的應用程序中有 jwt 身份驗證,這就是我在 startup.cs 類中實現的方式
services.AddAuthentication()
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
里面配置方法
app.UseAuthentication();
在控制器中使用屬性
[Authorize]
正常的身份驗證工作正常。 我想在驗證時檢查一些自定義的東西而不丟失默認的身份驗證過程,我的意思是我不想編寫我的全新身份驗證方法。
您應該能夠通過鏈接身份驗證方案來構建默認身份驗證。
首先,您可以實現自定義身份驗證處理程序:
public class CustomAuthenticationHandler : AuthenticationHandler<CustomAuthHandlerOptions>
{
public CustomAuthenticationHandler(IOptionsMonitor<CustomAuthHandlerOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
{
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
//Write custom logic here
return await Context.AuthenticateAsync(Scheme.Name);
}
}
public class CustomAuthHandlerOptions : AuthenticationSchemeOptions
{
public string MyCustomOptionsProp { get; set; }
}
然后您可以將方案添加到AuthenticationBuilder
:
services.AddAuthentication()
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
})
.AddScheme<CustomAuthHandlerOptions, CustomAuthenticationHandler>("CustomAuthJwt", options =>
{
options.MyCustomOptionsProp = "Custom Value";
});
我還沒有實際測試過這個,但我知道這種方法的想法是有效的,因為它已經在IdentityServer4.AccessTokenValidation Nuget Package 中實現了。 我的例子只是最簡單的版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.