Reputation: 4417
I have an MVC3 app and the user needs to be authenticated before they can access the site. I was logged in and was on a screen showing data, then i left. I came back an hour later, and by now the user has been automatically logged off. But when i clicked on a button to get data, without logging back in, I got the yellow screen of death cause my object was null. This is my Action:
[Authorize]
public ActionResult Index(string id)
I thought the [Authorize] attribute made sure to not execute this action unless they are authenticated, but apparently it doesnt or im not using it properly. So how do i use the [Authorize] or any other attribute to make sure the user is always authenticated and if they're not, take them to the login screen? Thanks
P.S. This only happens when a timeout has occurred. If i just try to access a view by typing in the URL and not logging in, i get the login screen as expected
Upvotes: 0
Views: 378
Reputation: 1038880
I came back an hour later, and by now the user has been automatically logged off
If the action is executed, this means that the user is not logged off. The [Authorize]
attribute works as expected.
I suspect that your problem has nothing to do with authentication. It has to do with ASP.NET Session that you are using. Please bear in mind that Forms Authentication cookie and ASP.NET Session are 2 completely different notions. So I guess that you have stored something into the ASP.NET Session when the user logged in. Except that the ASP.NET Session by default expires in 20 minutes and is configured independently of the forms authentication cookie timeout. So while the user authentication cookie is still valid and the user is authenticated it has lost its session because either the session expired or the web server simply recycled your application and everything you stored into the Session is of course lost.
This being said let's see the different possibilities that you have to workaround this problem:
<sessionState mode="Off" />
in your web.config and forget about the statefulness that the ASP.NET Session introduces in stateless applications. Write a custom Authorize attribute which in addition to checking whether the authentication cookie is valid it will check if the Session still contains values:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
return false;
}
return httpContext.Session["someKeyThatYouHaveStored"] != null;
}
}
and then use this custom attribute:
[MyAuthorize]
public ActionResult Index(string id)
Upvotes: 4