ASP.NET MVC2 global authentication
I'm new to ASP.NET MVC 2 and I ran into a simple problem.
The thing is that I want to force user to login to view my website. T开发者_StackOverflow社区hat means when user requests something like Home.Index or any other Controller.Action, I should check if user is logged in and if not, redirect request to Auth.LogIn.
I could check for authorization in every Action of each Controller, but I thought that there should be some more elegant approaches for this.
So. Is there?
Use the [Authorize]
attribute.
You can place it before any action for which you wan tto check authentication. If you place it on the controller class every action of that controller will be subject to authentication
Example
[Authorize]
public class MyController : Controller {
}
or
public class MyController : Controller {
[HttpGet]
[Authorize]
public ActionResult Index()
{
return View();
}
}
The Authorize attribute just checks if the user has been logged in or not. The login view where he redirect the user is defined in your web.config
file. If you check your web.config you will find a section like the following inside the system.web tag
<authentication mode="Forms">
<forms loginUrl="~/Login/LogOn" name=".td_gsl_login_cookie" timeout="30"
slidingExpiration="true"/>
</authentication>
The loginUrl
attribute is the controller action where the user get redirected if not logged in.
精彩评论