0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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: Check my answer Update for details
So, If I am authenticating the user manually, I meant, I want to authenticate the user using Sql Server. Once get the reply from database that the user is authenticated in that case how can I get to know using the above code that the user is authenticated or not ? I meant how can [Authorize] help me in this context ?
What do you mean exactly by "authenticating the user manually"? In My sample I am using form authentication with a SQL database. As long as your authentication provider is an ASP.NET authentication provider you dont have to worry about it. Your code will be' executed only if the user is logged in...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.