drinu16
drinu16

Reputation: 795

Redirect from Unathorized request to a new view

I want to redirect to a view, but the view is loading in the partial view which the [Authorize] attribute is on.

is there something else than response.redirect ?

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            string authUrl = this.redirectUrl; //passed from attribute NotifyUrl Property

            //if null, get it from config
            if (String.IsNullOrEmpty(authUrl))
            {
                authUrl = System.Web.Configuration.WebConfigurationManager.AppSettings["RolesAuthRedirectUrl"]; 
            }
            if (!String.IsNullOrEmpty(authUrl))
            {

                filterContext.HttpContext.Response.Redirect(authUrl); 
            }


        }

        base.HandleUnauthorizedRequest(filterContext);
    }




[AuthorizeUsers(Roles = "Administrator", NotifyUrl = "/CustomErrors/Error404")]
    public ActionResult addToCart(int ProductID, string Quantity)
    {

         ...
    }

Upvotes: 0

Views: 110

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

It appears that you are invoking the controller action that is decorated with this Authorize attribute using an AJAX call. And you want to fully reload the page if the user is not authorized.

Phil Haack wrote an very nice blog post illustrating how you could achieve that: http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx/

The idea is simple. Since you made an AJAX request to this controller action, the only way to move out from the partial is to make the redirect using javascript. So for example your AJAX code could detect if the contoller action returned 401 HTTP status code and then use the window.location.href to redirect away to the login page:

$.ajax({
    url: '/protected',
    type: 'POST',
    statusCode: {
        200: function (data) {
            // Success
        },
        401: function (data) {
            // Handle the 401 error here.
            window.location.href = '/login'
        }
    }
});

The only difficulty here is how to make the standard Authorize attribute return 401 instead of attempting to redirect to the login page. And Phil Haack illustrated the AspNetHaack NuGet which achieves this.

Upvotes: 1

Related Questions