0

Details

I'm using ASP.NET MVC with Angular. If I do a hard refresh (F5), it hits the attribute I created just fine.. also when the session cookies exist it accesses it fine. but say the user is on a certain page, and the session cookie expires while he's on it.. the code will still access my Angular code, but once it's supposed to hit my Controller or probably my Attribute first.. it doesn't. So nothing works on the webpage at that point and nor does it redirect to the Login screen.

I googled around and searched this website as well but haven't found anything that works.. Any help?

My Code

Attribute for all my Controllers EXCEPT by AccountController (it causes a Redirect loop for some reason??). I put this at the top of all my controllers.

[CustomFilters.VerifySession]

My Custom Attribute

public class CustomFilters
{
    public class VerifySessionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var userId = filterContext.HttpContext.Session["UserId"];
            var userName = filterContext.HttpContext.Session["UserName"];

            if (userId == null || userName == null)
                filterContext.Result = new RedirectResult(string.Format("/Account/Login"));
        }
    }
}

My Login Function

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model)
{
    ...
    Session["UserId"] = UserId;
    Session["UserName"] = sql.UserProfiles.Where(c => c.UserId == UserId).Select(x => x.UserName).FirstOrDefault();
    ...
}

Web.config

<system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="1" />  //set to 1 just for testing purposes
    </authentication>
    <sessionState timeout="1" />  //set to 1 just for testing purposes
</system.web>
5
  • Have you tried putting your code in the Session_End method of global.asax.cs ? Commented Jan 7, 2016 at 22:06
  • @Dan can you elaborate more? I'd like to try your suggestion Commented Jan 7, 2016 at 22:08
  • The Session_End method of the Global.asax.cs file fires when the session times out for a user. You can try putting a breakpoint there. You can add Global.asax.cs to you MVC project if it is not already there, it's not by default. Commented Jan 7, 2016 at 22:12
  • @Dan ah! i didn't know that! okay let me experiment with that and i'll get back to you. Thank you. Commented Jan 7, 2016 at 22:14
  • @Dan ah, it indeed does go into that function .. but there's no way for me to redirect to the login URL from that function as it errors. When I google how to, there doesn't seem to be a solution to do so unfortunately. TY for your input though Commented Jan 8, 2016 at 1:26

1 Answer 1

1

Not quite enough detail to figure out what's happening, so a couple thoughts:

First, the forms authentication module will redirect before an unauthenticated request hits your filters or controllers. Way it works is the forms module will intercept any 401 Unauthenticated responses generated anywhere in the application and replace them with 302 redirects to the login page.

Second, these redirects won't work on an ajax request. You didn't mention if you checked the responses in your browsers' dev tools, but if you send an ajax request with an expired cookie, the browser will automatically follow the redirect issued by the forms module but won't actually redirect the user to the login page--instead you'll simply get the HTML of the login page as response data in the ajax request.

So it sounds to me like the problem you are having is that the forms module is redirecting unauthenticated requests to the login page, but this just doesn't work for ajax requests made by the angular framework.

Basically what you need is some javascript code to recognize when it's getting an unauthenticated response and actually redirect the page to the login page instead of parsing the response. My own solution (not using angular) was to simply disable the 302 redirect on unauthenticated requests, then instead have javascript handle 401 responses: Best way to handle unauthenticated request in asp.net Web Api

Sign up to request clarification or add additional context in comments.

2 Comments

Hey Matthew, thanks for responding. After many hours of banging my head lol, I came to the conclusion that your 2nd paragraph on the ajax is actually correct. I am indeed receiving the HTML of the login page as a response data.. I'm trying to figure out how to detect this though so I can make a redirect in the Javascript. Any direction on how to do that? It seems like the status number is 200 no matter what. Thanks again
Unfortunately, browsers will follow the 302 automatically--there's no way to intercept that in javascript. You either need to have javascript examine the response text to determine if it looks like a login page, or you need to disable the asp.net module that converts 401 responses into 302s, which would have to be done in the code, not in the web.config.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.