Custom authorization
I'm trying to use my own authorization by creating a base controller and override the OnAuthorization method.
It works fine when authorization fails, but I get a 401 page when my checks succeed (but the default authorization checks fail).
protected override void OnAuthorization开发者_如何学JAVA(AuthorizationContext filterContext)
{
var roleAttribute = typeof(AuthorizeAttribute);
var attributes = filterContext.ActionDescriptor.GetCustomAttributes(roleAttribute, true);
if (attributes.Length == 0)
attributes = GetType().GetCustomAttributes(roleAttribute, true);
if (attributes.Length == 0)
return;
MvcHelper.Authenticate();
foreach (AuthorizeAttribute item in attributes)
{
if (!Thread.CurrentPrincipal.IsInRole(item.Roles))
{
filterContext.Result = new RedirectResult("~/Error/Unauthorized/" + "?MissingRole=" + item.Roles);
return;
}
}
//how do I prevent the default authorization here?
}
I've tried with filterContext.HttpContext.SkipAuthorization = true;
but it doesn't help.
I usually do this in an ActionFilter : https://gist.github.com/e297b435ceb8f022fb95
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext == null)
throw new ArgumentNullException("FilterContext");
if (AuthProvider == null)
throw new ArgumentNullException("IAuthProvider");
if (AuthProvider.Authenticate(filterContext) == false)
{
var req = filterContext.HttpContext.Request;
var response = filterContext.HttpContext.Response;
response.StatusCode = 401;
response.AddHeader("WWW-Authenticate", "Basic realm=\"Emergidata\"");
response.End();
}
else
{
var controller = filterContext.Controller as IAppController;
controller.DynamicSession= AuthProvider.AuthProviderContext;
}
}
I would do this in two steps:
- First I would secure the whole application so you explicitly must white list those controllers that should be available to anonymous users, read the section "Limitation of the LogonAuthorize filter approach" on http://blogs.msdn.com/b/rickandy/archive/2011/05/02/securing-your-asp-net-mvc-3-application.aspx. There you have one filter that you apply globally to limit the access to your application and one attribute that you apply to those actions you want to allow anonymous access to.
- The next step would be to implement another filter that you apply to those actions where you want the user to have a specific role or ability. This filter would inherit from
AuthorizeAttribute
.
精彩评论