将 ASP.Net MVC 中执行身份验证的控件的视图的身份验证设置为 true
在身份验证控件中,我使用以下行将用户标记为在系统中经过身份验证(检查密码后):
FormsAuth.SignIn(userName, rememberMe);
如果我重定向(这是标准行为),则一切正常。 但是,如果我立即显示视图,则检查用户是否经过身份验证的常用方法
Page.User.Identity.IsAuthenticated
Request.IsAuthenticated
将不起作用。 他们说用户没有经过身份验证。 如何使身份验证立即生效,或者是否有其他方法可以检查用户刚刚登录的时间?
In the authentication control I have the following line to mark a user as authenticated in the system (after checking out the password):
FormsAuth.SignIn(userName, rememberMe);
and if I redirect, which is the standard behvaior, everything is ok. But if I show a view right away, the usual ways to check whether a user is authenticated:
Page.User.Identity.IsAuthenticated
Request.IsAuthenticated
don't work. They say the user is not authenticate. How can I make the authentication effective immediately or is there another way to check that would allow me to find out when the user just logged in?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
FormsAuth.SignIn
是从 Visual Studio 创建新的 ASP.NET MVC 项目时生成的函数。该函数只需调用 FormsAuthentication.SetAuthCookie,根据文档,在响应中设置身份验证cookie。
这解释了为什么如果您重定向它会起作用(因为客户端将在后续请求中回放 cookie),但在调用之后就不起作用。
重定向是执行此操作的正确/传统方法,但如果您绝对坚持在重定向之前检查身份验证,那么您可以在会话状态中创建一个 IsAuthenticated 标志并在检查时引用该标志。
FormsAuth.SignIn
is a function which is generated when you create a new ASP.NET MVC project from Visual Studio.That function simply calls FormsAuthentication.SetAuthCookie, which according to the docs, sets the authentication cookie in the response.
This explains why it works if you redirect (because the client will play back the cookie in the subsequent request), but not right after the call.
Redirecting is the right/conventional way to do this, but if you absolutely insist on checking authentication before a redirect, then you could create an IsAuthenticated flag in session state and refer to that when checking.
在您的控制器上,您应该能够使用以下命令来检查它们是否已通过身份验证。
当您从一个页面移动到另一个页面时,我会检查以确保您的 AccountController 正确保存了主体对象。
On your Controllers, you should be able to use the following to check if they're authenticated.
I would check to make sure that your AccountController is properly saving the Principal object as you move from page to page.
除了使用 FormsAuth.Signin 或 FormsAuthentication.SetAuthCookie 之外,您还可以在执行登录代码时在登录控件中手动设置 User.Identity。 如上所述,原因是 FOrmsAuth.SignIn 只是设置下次在 Request_OnAuthenticate 事件中拾取的身份验证 cookie。 (这只是解码 cookie 并设置 HttpContext.User 属性)
In addition to using the FormsAuth.Signin or FormsAuthentication.SetAuthCookie, you can also set the User.Identity manually in your sign-in control when the sign-in code executes. As written above, the reason is because the FOrmsAuth.SignIn simply sets the authentication cookie to be picked up next time in the Request_OnAuthenticate event. (Which simply decodes the cookie and sets the HttpContext.User property)