我想了解如何修复我
在代码中使用 FormsAuthentication.SetAuthCookie(user.Login, false); 进行登录时 遇到的行为
我的控制器的每个方法都有 [Authorize] 属性
我的 web.config
:
<authentication mode="Forms">
<forms loginUrl="~/Login/Index" timeout="10"/>
</authentication>
问题是有时我不转到登录页面并且 Authorize
属性通过,所以我的控制器方法崩溃(因为没有会话数据)。为了解决这个问题,我清除了浏览器缓存,并在浏览器工作后重新启动浏览器。
我认为我的登录逻辑有问题?有人可以解释它以及如何以正确的方式做到这一点。
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 correct way.
发布评论
评论(1)
表单身份验证和 ASP.NET MVC 授权筛选器都不依赖于 ASP.NET 会话状态。因此,如果控制器方法由于缺少会话数据而崩溃,那么它与假设这种关系的代码有关。请参阅本文了解 Authorize 如何与 ASP.NET 身份验证配合使用。
我相信您的问题源于您假设表单身份验证与会话状态同义。但是您可以在不进行身份验证的情况下获得会话状态。两者使用不同的机制并具有不同的超时。因此,如果您在登录页面中以会话状态放置一些数据,那么您的会话可能会过期,但身份验证仍然有效(因此,您不会被带到登录页面)。一个简单的解决方案可以是同步会话和身份验证超时,但这在应用程序重新启动时不起作用。最好的方法是检查相关会话数据,如果不存在,则强制重新登录或使用经过身份验证的用户的主体/身份信息来恢复会话中的数据。我更喜欢后面的方法。
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.