我有一个项目,其中网络通过身份进行身份验证,我想将 JWT 用于 API。我应该做哪些改变才能同时使用两者?
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options =>
{
options.LoginPath = "/Login";
options.LogoutPath = "/Logout";
options.ExpireTimeSpan = TimeSpan.FromMinutes(43200);
});
同时使用JWT和Identity
您可以尝试以下代码:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
//add cookie scheme
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
//add jwt scheme
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>{...}
);
//Add a policy called "Jwt_Or_Cookie" to allow either jwt or cookie.
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("Jwt_Or_Cookie", policy =>
{
policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
policy.AuthenticationSchemes.Add(CookieAuthenticationDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
});
});
然后你可以使用这个允许这两种方案的策略
[Authorize(Policy = "Jwt_Or_Cookie")]
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{...}