简体   繁体   English

为什么[Authorize]属性不起作用?

[英]Why is the [Authorize] attribute not working?

I have an ASP.NET MVC5 web site, and when the user logs in, I do the following... 我有一个ASP.NET MVC5网站,当用户登录时,我执行以下操作...

FormsAuthentication.SetAuthCookie(customer.GetSalutation, rememberMe);

I have a CustomerController, that is decorated with the [Authorize] attribute... 我有一个CustomerController,它装饰有[Authorize]属性...

[Authorize]
public class CustomerController : Controller {
  public ActionResult Ferret() {
    return View();
  }
}

...but this seems to be ignored. ...但是这似乎被忽略了。 If I try to access /Customer/Ferret, it allows is quite happily. 如果我尝试访问/ Customer / Ferret,则很高兴。

I tried adding [Authorize] to the controller method as well, but that didn't make any difference. 我也尝试在控制器方法中添加[Authorize],但这没有任何区别。

What am I doing wrong? 我究竟做错了什么?

Update - found the problem! 更新-发现了问题!

I realised that the situation isn't quite as I described. 我意识到情况并非我所描述的那样。 If I log out and try and access /Customer/Ferret, I get sent to the log-in page as expected. 如果我注销并尝试访问/ Customer / Ferret,则会按预期发送到登录页面。

I have a static class LoggedInUser, which contains a property called Me, which holds info about the logged in user. 我有一个静态类LoggedInUser,它包含一个名为Me的属性,该属性保存有关已登录用户的信息。

The problem comes when I upload a new version of the site (which is happening quite a lot at the moment, as we are actively developing and rolling out new versions several times a day). 当我上载网站的新版本时,问题就来了(由于我们每天都在积极地开发和推出新版本,所以目前正在发生很多事情)。 If someone is logged in, and I update the site, the site gets recompiled. 如果有人登录,并且我更新了站点,则将重新编译该站点。 Their auth cookie doesn't get removed, as they didn't log out, but when they try to access the page, the auth info is not there, so I get a null reference exception on the LoggedInuser class. 他们的身份验证cookie不会被删除,因为他们没有注销,但是当他们尝试访问该页面时,身份验证信息不存在,因此LoggedInuser类上出现了空引用异常。

I added the following to Global.asax and it fixed the problem... 我将以下内容添加到Global.asax中,它解决了该问题...

protected void Application_BeginRequest() {
  if (LoggedInUser.Me == null || LoggedInUser.Me.LgID == 0) {
    FormsAuthentication.SignOut();
  }
}

That did the trick. 做到了。 If they try to access a page after a recompile, LoggedInUser.Me will be null (or LgID will be zero) and they will be logged out, which will send them to the log-in page. 如果他们在重新编译后尝试访问页面,则LoggedInUser.Me将为null(或LgID为零),并且将注销它们,这会将它们发送到登录页面。

Don't know if this will help anyone, but I'm posting it in case. 不知道这是否对任何人都有帮助,但我以防万一。

Make sure, you remove the set cookie on user signout. 确保在用户注销时删除设置的cookie。 If it is still there, it will consider the user to be logged in and by pass the authorize. 如果仍然存在,它将认为用户已登录并通过了授权。

Call FormsAuthentication.SignOut(); 调用FormsAuthentication.SignOut(); on you signout event. 在您退出活动上。

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

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