Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict access to certain actions in controller in ASP.net MVC

I am new to ASP.net MVC and created my first web application using it. In my application I am using database authentication. I have created Login action in controller which checks entered username and password exist in DB or not, If it exist then put required values in Session and redirect user to pages as per his rights else redirect user to login page. Like this

public ActionResult Login()
{
   if(uservalid)
   {
      //set session values and redirect to dashboard
   }
   else
   {
      //redirect to login
   }
}

In my application there are some functionality that can only be accessed when user is logged-in. I want to check whether user is logged-in or not before user try to access these functionality and if he is not logged-in or not have rights then redirect to login page or show some error message.

public ActionResult SomeAction()
{
   //Available only when user is logged-in
}

So how do I check whether user is logged-in or not and give access to action. I read about Authorize attribute but don't know how to use it as I am using database authentication.

like image 789
CodeWarrior Avatar asked Nov 21 '13 14:11

CodeWarrior


1 Answers

If you are using FormsAuthentication you don't need to use ASP.NET session to track the currently authenticated user.

I read about Authorize attribute but don't know how to use it as I am using database authentication.

Assuming you went with FormsAuthentication, once you have validated the credentials of the user you should set a forms authentication cookie:

public ActionResult Login()
{
   if(uservalid)
   {
      FormsAuthentication.SetAuthCookie("username", false);
      return RedirectToAction("SomeProtectedAction");
   }
   else
   {
      //redirect to login
   }
}

and then:

[Authorize]
public ActionResult SomeAction()
{
   string currentlyLoggedInUser = User.Identity.Name;
}

By the way if you create a new ASP.NET MVC application using the internet template in Visual Studio you might take a look at the AccountController which is responsible for authenticating users and setting forms authentication cookies. Of course you could throw all the Entity Framework crap out of it and implement your own credentials validation against your own database tables.

like image 127
Darin Dimitrov Avatar answered Oct 06 '22 17:10

Darin Dimitrov