在Startup.cs文件中,在ConfigureServices方法中配置Identity服务并指定默认认证方案:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "CustomScheme";
options.DefaultSignInScheme = "CustomScheme";
options.DefaultChallengeScheme = "CustomScheme";
})
.AddCookie("CustomScheme", options =>
{
options.AccessDeniedPath = "/Account/AccessDenied";
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Lax;
options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
options.SlidingExpiration = true;
});
在Configure方法中,使用UseAuthentication方法指定身份验证:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
这里的CustomScheme是自定义方案名称,可以更改为自己的名称。AccessDeniedPath、LoginPath和LogoutPath是用于重定向的路径,可以更改为自己需要的路径。然后,在控制器或者Action中添加[Authorize(AuthenticationSchemes = "CustomScheme")]属性即可使用自定义方案的身份验证重定向。