net framework 47 mvc中怎么实现部分方法使用cookie认证部分使用jwt认证?
在 .NET Framework 4.7 MVC 中,可以通过在控制器中的方法上添加特性来实现部分方法使用 cookie 认证,部分方法使用 JWT 认证。
首先,在 Startup.cs 中配置 JWT 认证服务,例如:
public void ConfigureServices(IServiceCollection services)
{
// 添加身份验证服务
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"]))
};
});
// 添加 MVC 服务
services.AddMvc();
}
然后,在控制器中的方法上添加相应的特性,例如:
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public IActionResult MethodWithCookieAuthentication()
{
// 处理方法
}
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public IActionResult MethodWithJwtAuthentication()
{
// 处理方法
}
在上述示例中,MethodWithCookieAuthentication 方法使用 cookie 认证,特性为 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)];MethodWithJwtAuthentication 方法使用 JWT 认证,特性为 [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]。
请注意,如果未指定特定的认证方案,则默认情况下使用 HttpContext.AuthenticateAsync() 方法进行身份验证。因此,您需要在 Startup.cs 中明确指定默认的身份验证方案,例如:
public void ConfigureServices(IServiceCollection services)
{
// 添加身份验证服务
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"]))
};
});
// 添加 MVC 服务
services.AddMvc();
}
在此示例中,DefaultAuthenticateScheme 和 DefaultChallengeScheme 均设置为 CookieAuthenticationDefaults.AuthenticationScheme,这意味着默认情况下使用 cookie 认证。如果需要使用不同的身份验证方案,请相应地修改特性中的 AuthenticationSchemes 属性。
原文地址: http://www.cveoy.top/t/topic/bLx6 著作权归作者所有。请勿转载和采集!