Authorize attribute not working sometimes times in my project
I want to understand how to fix the behavior I'm encountering
I'm doing my login in code with FormsAuthentication.SetAuthCookie(user.Login, false);
Each method of my controller has the [Authorize] attribute
My web.config
:
<authentication mode="Forms">
<forms loginUrl="~/Login/Index" timeout="10"/>
</authentication>
The problem is sometimes I dont go to the login page and the Authorize
attribute passes so my controller method crashes (because there's no session data). To fix it I clear the browser cache and restart the browser only after its working.
I think there's some trouble in my login logic? Can someone explain it and how to do it in the co开发者_StackOverflowrrect way.
Both Forms Authentication and ASP.NET MVC Authorize filter don't have any dependency on ASP.NET Session State. So if controller method crashes due to lack of session data then its something to do with your code that assumes such a relationship. See this article to understand how Authorize works with ASP.NET authentication.
I believe that your issue originates because you are assuming forms authentication synonymous to session state. But you can have session state without authenticating. Both uses different mechanism and have different time outs. So if you are putting up some data in session state in login page then it is possible that your session get expired but the authentication remains valid (and hence, you will not be taken to the login page). A simple solution can be syncing session and authentication time out but that will not work over application restarts. The best way would be to check relevant session data and if it does not exist then either force re-login or use authenticated user's principal/identity information to restore the data in the session. I would prefer the later approach.
精彩评论