Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc authorize attribute redirect

Tags:

c#

asp.net-mvc

In my application I have made a custom Attribute like this

public class AdminAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized || Auth.CurrentAdminUser == null)
        {
            return false;
        }
        else
        {
            return (SuperAdmin.Get(Auth.CurrentAdminUser.Id) != null) ? true : false;
        }
    }
}

It is working fine, but what I want is to do a redirect based on if the user is not logged in then take to log in page and if the user is logged in but is not a super admin take him to not authorize page.

What happens now is that all the unauthorized stuff is redirected to this page through web.config file,

<authentication mode="Forms">
  <forms loginUrl="~/Site/NotAuthorize" timeout="2880" />
  <!-- this is where we can set up that if you are not authenticated, where should you go then?-->
</authentication> 

Any help would be much appreciated.

like image 201
mohsinali1317 Avatar asked Apr 27 '26 20:04

mohsinali1317


1 Answers

You should override HandleUnauthorizedRequest

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

    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "xxx", action = "xxx", area = "" }));
}
like image 185
ohlmar Avatar answered Apr 29 '26 09:04

ohlmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!