您可以使用身份验证中间件和Authorize
重定向登录页面的属性。对于你的情况也使用AuthenticationScheme
看起来很合理。
第一次使用(我假设你想使用cookie中间件)cookie身份验证中间件:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "AdminCookieScheme",
LoginPath = new PathString("/Admin/Account/Login/"),
AccessDeniedPath = new PathString("/Admin/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieName="AdminCookies"
});
然后使用Authorize
此方案的属性:
[Authorize(ActiveAuthenticationSchemes = "AdminCookieScheme")]
另一种选择是使用UseWhen https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Samples/blob/cdc53b2a132b73bc10fd4dcbb91b169634a589a1/samples/Mvc/Mvc.Server/Extensions/AppBuilderExtensions.cs分离管理员和默认身份验证:
app.UseWhen(x => x.Request.Path.Value.StartsWith("/Admin"), builder =>
{
builder.UseCookieAuthentication(new CookieAuthenticationOptions()
{
LoginPath = new PathString("/Admin/Account/Login/"),
AccessDeniedPath = new PathString("/Admin/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
});
然后只需使用Authorize
属性。