简体   繁体   English

在我的项目中,授权属性有时不工作

[英]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); 我正在使用FormsAuthentication.SetAuthCookie(user.Login, false);进行代码登录FormsAuthentication.SetAuthCookie(user.Login, false); Each method of my controller has the [Authorize] attribute 我的控制器的每个方法都有[Authorize]属性

My web.config : 我的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). 问题是有时我没有进入登录页面并且Authorize属性通过,因此我的控制器方法崩溃(因为没有会话数据)。 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. 有人可以解释它以及如何以正确的方式做到这一点。

Both Forms Authentication and ASP.NET MVC Authorize filter don't have any dependency on ASP.NET Session State. Forms Authentication和ASP.NET MVC Authorize过滤器都不依赖于ASP.NET会话状态。 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. 请参阅此文章以了解Authorize如何使用ASP.NET身份验证。

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. 我更喜欢后来的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM