ASP.NET Core中的自定义授权属性
我正在研究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核心中为自定义操作设置这样的filter?
您可以使用身份validation中间件和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来分离管理员和默认身份validation:
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
属性。