1

I've been through a couple of questions and none of them seem to fit my problem: This, and this.

While these questions do accurately depict creating a custom Authorize Attribute (So no need to go through that in any possible answers), my problem goes a little further:

I need to redirect to specific Views based on which role is being Authorized.)

Example:

[Authorize(Role = "Admin")]

needs to redirect to a different View than:

[Authorize(Role = "User")]

If this is even possible, please provide me with a solution.

Thanks.

Community
  • 1
  • 1
Terrance00
  • 1,658
  • 1
  • 20
  • 29
  • The Objective of `Authorize` attribute is not redirection to designate landing page. I would recommend you you create a new common action and then redirect it to designate view as per role. – Satpal Aug 28 '15 at 08:16
  • Okay I understand. Was hoping for some clever trick though. Thanks! – Terrance00 Aug 28 '15 at 08:18
  • Most of the time simple solution is the best solution. I personally try to keep thing simple. – Satpal Aug 28 '15 at 08:19

2 Answers2

1

Yes there is.Here is the code.

public class CustomActionAttribute : FilterAttribute, IActionFilter
{
    string _role;
    string _redirect;

    public CustomRedirectFilter(string role, string redirect)
    {
       _role = role;
       _redirect = redirect;
    }
    void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(CheckDatabaseToCheckUserRole == _role)
        {
             filterContext.Result = new RedirectResult(_redirect);    
        }
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {

    }


}

USAGE:

[CustomRedirectFilter("Admin","/Admin")]
TotalWar
  • 335
  • 1
  • 6
  • 16
1

In MVC you can create a custom authorization filter and do your redirect in HandleUnauthorizedRequest:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeRedirect : AuthorizeAttribute
{
    public string RedirectUrl = "~/Error/Unauthorized";

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        base.HandleUnauthorizedRequest(filterContext);

        if (filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new RedirectResult(RedirectUrl);
        }
    }
}

I think you are looking at it from the wrong direction. You shouldn't use multiple attributes for each role, but get the current user's role(s) in HandleUnauthorizedRequest and write your redirect logic based on that.

Attila Szasz
  • 3,033
  • 3
  • 25
  • 39