How should I check if a user is authenticated in MVC5?

user1679941 picture user1679941 · Sep 30, 2013 · Viewed 50.6k times · Source

I have seen the following two accessible booleans:

  • System.Web.Mvc.Controller.User.Identity.IsAuthenticated
  • System.Web.Mvc.Controller.Request.IsAuthenticated

Is there a difference between these. They both seem to do the same thing so I am not sure which to use.

What I would like to do is:

@if (User.Identity.IsAuthenticated) {
  if (User.IsInRole("Admin")) {
    @Html.ActionLink("Admin", "AdminController")        
  }
}

or

@if (Request.IsAuthenticated) {
  if (User.IsInRole("Admin")) {
    @Html.ActionLink("Admin", "AdminController")        
  }
}

Would either of the above work equally well ?

Answer

Darin Dimitrov picture Darin Dimitrov · Sep 30, 2013

There's no difference. The only difference is that if the user is not authenticated User.Identity might be null and thus you might get a NRE, whereas with the second approach, internally there's a check for this and is safer.

Here's how the Request.IsAuthenticated method is implemented:

public bool IsAuthenticated
{
    get
    {
        return this._context.User != null && 
               this._context.User.Identity != null &&
               this._context.User.Identity.IsAuthenticated;
    }
}

Basically it's a bit safer than the first one.