问题
i'm working on asp.net core and i don't understand some things. for example in mvc.net 5 we can filter and authorize action with create class from AuthorizeAttribute and set attribute to actions like this:
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");
}
}
but in asp.net core we don't have AuthorizeAttribute ... how can i set filter like this in asp.net core for custom actions ?
回答1:
You can use authentication middleware and Authorize
attirbute to redirect login page. For your case also using AuthenticationScheme
seems reasonable.
First use(i assume you want use cookie middleware) cookie authentication middleware:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "AdminCookieScheme",
LoginPath = new PathString("/Admin/Account/Login/"),
AccessDeniedPath = new PathString("/Admin/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieName="AdminCookies"
});
and then use Authorize
attribute with this scheme:
[Authorize(ActiveAuthenticationSchemes = "AdminCookieScheme")]
Another option is using UseWhen to seperate admin and default authentication:
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
});
});
And then just use Authorize
attribute.
来源:https://stackoverflow.com/questions/38264791/custom-authorization-attributes-in-asp-net-core