gpt4 book ai didi

c# - 如何在 dot net core 中修改默认的本地 JWT 身份验证

转载 作者:太空宇宙 更新时间:2023-11-03 12:07:50 26 4
gpt4 key购买 nike

我的应用程序中有 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();

在 Controller 中使用的属性

[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 中实现了。 .我的示例只是其中最简单的版本。

关于c# - 如何在 dot net core 中修改默认的本地 JWT 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54011111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com