ygetarts ygetarts - 1 month ago 8
C# Question

C# mvc5 - Easy way to check if user is authenticated in each controller method

I have a controller that I only want authenticated users to be able to access. Do I have to put a check in each method in my controller to verify a user is authenticated, or is there another way to handle this? Can I use annotations to do this instead?

Example from my controller:

public ActionResult Index()
{
if (UserVerified())
{
...
}
return RedirectToAction("Login", "Account");
}

public ActionResult FacebookLogin()
{
if (UserVerified())
{
....
}

return RedirectToAction("Login", "Account");
}

private bool UserVerified()
{
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
return true;
}
return false;
}

Answer

You can use AuthorizeAttribute for it.
Put it to every action.

[Authorize]
public ActionResult Index()
{
}

[Authorize]
public ActionResult FacebookLogin()
{
}

It will do the whole work for you. It checks whether the currect user is authenticated. If he is authenticated - proceeds to the action, if he is not - returns to the home page.

You can also add this attribute to a controller. Then all actions will require authorization.

[Authorize]
public class HomeController
{
    public ActionResult Index()
    {
    }

    public ActionResult FacebookLogin()
    {
    }
}

Update: And, yes, as Kamil said. Read this article, please.
http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

You spend some time now and will spend much less time having questions about ASP.NET authentication in future.

By the way, you don't need to check for

User != null && User.Identity != null

If you are using default authentication then you can be always sure that User.Identity is a proper object. You can access User.Identity.IsAuthenticated directly.

Comments