views:

12

answers:

1

Hey there.

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

A: 

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.

Lorenzo
Thanks for a quick answer. Still it is a little bit unclear to me how [Authorize] works and how it considers which View to load.
Paul
@Paul: Check my answer Update for details
Lorenzo
That makes sense now. Thanks a lot!
Paul