ASP.NET MVC 2 RedirectToSignin

Thursday, August 19, 2010 / Posted by Luke Puplett /

If, for whatever reason, you cannot use the [Authorize] attribute on an action method, or as in my case, you have an unusual architecture, then this helpful method directs a visitor back to the sign-in or login screen and then re-runs the original action. It’s designed to work exactly as the AuthorizeAttribute works, but with the difference that you can do your own IsAuthorised logic within the method.

An application I’m working on has a WCF service which is where customers are logged-in. The MVC application simply packages up the web front end and ships all requests, CRUD ops, everything into service calls and then paints the results out via ASP.NET/HTML.

When a customer logs in to my MVC 2 app, it’s really just calling Login on the WCF Authentication Service – the MVC app doesn’t keep track of sessions and is truly stateless. The MVC app does, however, use forms authentication and so the cookie can say “yep, customer is signed-in” while the WCF service says, “Uh uh. This customer’s session expired.”

This means that my action methods with [Authorize] run, but then fail. I wrote this method to redirect the customer to the sign-in box, and then continue to execute the original action, using the returnUrl.


protected ActionResult RedirectToSignin(
    string returnAction, 
    string returnController, 
    object returnRouteValues, 
    RequestContext requestContext)
    UrlHelper u = new UrlHelper(requestContext);
    string returnUrl = UrlHelper.GenerateUrl(
        null, returnAction, returnController, new RouteValueDictionary(returnRouteValues),
        u.RouteCollection, requestContext, true);

    string baseAddress = String.Format("{0}://{1}"
        HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority);

    return Redirect(String.Format("{0}/Customer/Signin?returnUrl={1}"
        baseAddress, returnUrl));

Now within my action method, if I get a null or a fault from my service, I return RedirectToSignin(xyz) instead of returning an error. After sign-in, the action is called again and all is good in the hood.

Labels: , , ,


Comment by Luke Puplett on Thursday, August 19, 2010

And before you say it, yes the RequestContext argument becomes surplus once you put this method in your controller, i.e. you can just use this.Request.RequestContext

Post a Comment