我正在使用asp.net核心而且我不了解一些事情。 例如,在mvc.net 5中,我们可以使用AuthorizeAttribute中的create class过滤和授权操作,并将属性设置为这样的操作:
public class AdminAuthorize : AuthorizeAttribute {
public override void OnAuthorization(AuthorizationContext filterContext) {
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult)
filterContext.Result = new RedirectResult("/Admin/Account/Login");
}
}
但是在asp.net核心我们没有AuthorizeAttribute ...... 如何在asp.net核心中为自定义操作设置这样的过滤器?
答案 0 :(得分:8)
您可以使用身份验证中间件和Authorize
attirbute重定向登录页面。对于您的情况,使用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分隔管理员和默认身份验证:
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
属性。