Authentication asp.NETCore2.2中的多种身份验证方法
在.NETCore中是否有使用JWT承载身份验证和自定义身份验证方法的方法?我希望所有操作都默认为JWT,但在少数情况下,我希望使用自定义身份验证头。我终于找到了方法。本例默认使用JWT身份验证,在某些罕见的情况下使用自定义身份验证。请注意,从我所读到的内容来看,微软似乎不鼓励编写自己的auth。请自担风险使用 首先,将此代码添加到startup.cs ConfigureServices方法中,以确保全局应用身份验证Authentication asp.NETCore2.2中的多种身份验证方法,authentication,asp.net-core,.net-core,Authentication,Asp.net Core,.net Core,在.NETCore中是否有使用JWT承载身份验证和自定义身份验证方法的方法?我希望所有操作都默认为JWT,但在少数情况下,我希望使用自定义身份验证头。我终于找到了方法。本例默认使用JWT身份验证,在某些罕见的情况下使用自定义身份验证。请注意,从我所读到的内容来看,微软似乎不鼓励编写自己的auth。请自担风险使用 首先,将此代码添加到startup.cs ConfigureServices方法中,以确保全局应用身份验证 services.AddMvc(options => {
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
然后,添加它来配置您想要使用的方案(在我们的例子中是JWT和Custom)
最后,添加身份验证处理程序以实现自定义身份验证逻辑
public class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
{
public CustomAuthHandler(
IOptionsMonitor<CustomAuthOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock) : base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
// Auth logic goes here
if (!Request.Headers....)
{
return Task.FromResult(AuthenticateResult.Fail("Authentication Failed."));
}
// Create authenticated user
ClaimsPrincipal principal = .... ;
List<ClaimsIdentity> identities =
new List<ClaimsIdentity> {
new ClaimsIdentity(CustomAuthOptions.CustomAuthType)};
AuthenticationTicket ticket =
new AuthenticationTicket(
new ClaimsPrincipal(identities), CustomAuthOptions.Scheme);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
现在,JWT身份验证将自动应用于所有操作,而自定义身份验证将仅添加到将Authorize属性设置为自定义方案的操作
我希望这对某人有所帮助。这个问题似乎是直截了当的。你查过文件了吗?你能告诉我到目前为止你都做了些什么吗?你被困在哪里了?如果您不确定从何处开始,您可以在此处查看官方文档:例如,basic auth:This naswer非常有用:“使用多个JWT承载身份验证”
public class CustomAuthOptions : AuthenticationSchemeOptions
{
public const string Scheme = "custom auth";
public const string CustomAuthType = "custom auth type";
}
public class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
{
public CustomAuthHandler(
IOptionsMonitor<CustomAuthOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock) : base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
// Auth logic goes here
if (!Request.Headers....)
{
return Task.FromResult(AuthenticateResult.Fail("Authentication Failed."));
}
// Create authenticated user
ClaimsPrincipal principal = .... ;
List<ClaimsIdentity> identities =
new List<ClaimsIdentity> {
new ClaimsIdentity(CustomAuthOptions.CustomAuthType)};
AuthenticationTicket ticket =
new AuthenticationTicket(
new ClaimsPrincipal(identities), CustomAuthOptions.Scheme);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
[HttpGet]
[Authorize(AuthenticationSchemes = CustomAuthOptions.Scheme)]
public HttpResponseMessage Get()
{
....
}