Search code examples
asp.net-mvcazure-active-directoryadal

AuthorizeAttribute adal signout MVC


I have created a custom Authorize attribute based on AAD groups in MVC. If I return false in the attribute the applications goes into an infinite loop on the login page. How do you signoff the user from an custom authorize attribute when using adal in an MVC application?


Solution

  • When the user is authenticated but does not have the role(false returned in custom attribute) the authorize attribute will change the response to 401. It is only when the user is authenticated and have the role (true returned in custom attribute) that the authorize attribute won’t change the response.

    If you are using FormsAuthentication or the OWIN Cookie Authentication Middleware and the user is already logged in , he will be redirected to the login page again, which is kind of weird if you thing about it. "I've already logged in, and now I'm back do the log in page just because I clicked some link, and no one told me why this just happened."

    AuthorizeAttribute provides a protected virtual method named HandleUnauthorizedRequest that you can override, checking whether user is authenticated and show an erro page . For example :

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
            {
                if (filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
                }
                else
                {
                    base.HandleUnauthorizedRequest(filterContext);
                }
            }
    

    You could also redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary(
                        new
                            { 
                                controller = "Error", 
                                action = "Unauthorised" 
                            })
                    );
    }
    

    Please read here for more details .