如何在ASP中使用多重身份验证.NET Core 3.1



我想在我的项目中使用JWT身份验证和cookie身份验证,但在启动时添加身份验证配置时,其中一个不起作用。

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(option =>
{
option.LoginPath = "/Login";
option.LogoutPath = "/Logout";
option.ExpireTimeSpan = TimeSpan.FromDays(500);
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "https://localhost:44382",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("xxxxxxx"))
};
});

我认为您不需要单独添加身份验证,但您可以用简单的方式进行,它对您来说会很好。

services.AddAuthentication()
.AddCookie(options => {
here configuration for  cookie
options.LoginPath = "/Account/login";
options.LogoutPath = "/Account/Forbidden/";
})
.AddJwtBearer(options => {
here configuration for jwt 
options.Audience = "";
options.Authority = "";
});

您可以这样设置您的配置文件(这里我使用的是.Net6(

builder.Services.AddAuthentication(options => {
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
})
.AddCookie(x=> {
x.LoginPath = "/api/Hello";
});

然后您可以选择其中一个或全部来验证

//use all of them
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] 
[Route("[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
//...... 
}
//just use cookie authentication
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] 
[Route("[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
//...... 
}

最新更新