Multiple authentication methods in asp.Net core 2.2



有没有办法在.net核心中使用JWT承载身份验证和自定义身份验证方法?我希望所有操作都默认为JWT,除非在少数情况下我希望使用自定义身份验证头。

我终于明白了如何做到这一点。这个例子默认使用JWT身份验证,在某些罕见的情况下使用自定义身份验证。请注意,从我读到的内容来看,微软似乎不鼓励编写自己的授权。请自行承担使用风险。

首先,将此代码添加到startup.cs ConfigureServices方法中,以确保全局应用身份验证。

services.AddMvc(options => 
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})

然后,添加它来配置您想要使用的方案(在我们的案例中是JWT和Custom)。

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
// Jwt Authentication
.AddJwtBearer(options =>
{
options.Audience = ".......";
options.Authority = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_...";
})
// Custom auth
.AddScheme<CustomAuthOptions, 
CustomAuthHandler>(CustomAuthOptions.DefaultScheme, options => { });

接下来创建一个类来保存您的自定义身份验证选项:

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));
}
}

最后,为了将其结合在一起,请为您希望在上使用自定义授权的操作添加一个authorize属性

[HttpGet]
[Authorize(AuthenticationSchemes = CustomAuthOptions.Scheme)]
public HttpResponseMessage Get()
{
....
}

现在,JWT身份验证将自动应用于所有操作,而自定义身份验证将仅添加到将Authorize属性设置为自定义方案的操作中。

我希望这能帮助到别人。

最新更新