Avrohom Yisroel
Avrohom Yisroel

Reputation: 9472

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...

FormsAuthentication.SetAuthCookie(customer.GetSalutation, rememberMe);

I have a CustomerController, that is decorated with the [Authorize] attribute...

[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.

I tried adding [Authorize] to the controller method as well, but that didn't make any difference.

What am I doing wrong?

Upvotes: 0

Views: 1379

Answers (2)

Avrohom Yisroel
Avrohom Yisroel

Reputation: 9472

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.

I have a static class LoggedInUser, which contains a property called Me, which holds info about the logged in user.

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.

I added the following to Global.asax and it fixed the problem...

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.

Don't know if this will help anyone, but I'm posting it in case.

Upvotes: 1

Ashish Charan
Ashish Charan

Reputation: 2387

Make sure, you remove the set cookie on user signout. If it is still there, it will consider the user to be logged in and by pass the authorize.

Call FormsAuthentication.SignOut(); on you signout event.

Upvotes: 0

Related Questions