I have a scenario that I haven't been able to solve:
I'm toying around with creating my own custom authorization attribute for mvc. The main bit of functionality I would like to add is to have the ability to change where the user gets redirected if they are not in a certain role. I don't mind that the system sends them back to the login page if they're not authenticated, but I would like to choose where to send them if they are authenticated but not allowed to access that action method.
Here's is what I would like to do:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public string Action;
public string Controller;
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
// if User is authenticated but not in the correct role
string url = Url.Action(this.Action, this.Controller);
httpContext.Response.Redirect(url);
}
}
And as an added bonus I would like to have access to ViewContext and TempData before I do the redirect.
Any thoughts on how I could get instantiate a UrlHelper and ViewContext in the attribute?
If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.
One of the new features in ASP.NET MVC 4 is the AllowAnonymous Attribute that helps you secure an entire ASP.NET MVC 4 Website or Controller while providing a convenient means of allowing anonymous users access to certain controller actions, like the login and register Actions.
The Authorize attribute enables you to restrict access to resources based on roles. It is a declarative attribute that can be applied to a controller or an action method. If you specify this attribute without any arguments, it only checks if the user is authenticated.
You could override the OnAuthorization
method:
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
// Call the AuthorizeCore which should return true or false
if (!this.AuthorizeCore(filterContext.HttpContext))
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary()
{
{ "controller", "home" },
{ "action", "about" },
{ "id", "foo" },
});
}
}
As far as ViewData and TempData are concerned: filterContext.Controller.ViewData
and filterContext.Controller.TempData
should work inside the OnAuthorization
method. And finally if you wish to use an UrlHelper
(in this case there's no need because RedirectToRouteResult
is better) you could instantiate it:
var urlHelper = new UrlHelper(filterContext.RequestContext);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With