Redirect to login page in some session validation condition

In C # with MVC, I want to write a generic utility or class in which if a particular conditoin fails to redirect to the login page.

For example: When a user is logged into the website, the user account will be added to the session. To go to the "ManageUsers" page, the user must be logged in as an administrator, otherwise I need to be redirected to the login page. I need to check this condition on some other similar pages as well. I don't want to check that the user is an administrator or a regular user when logging in. I need to test this in the general class.

Any suggestions?

+1


a source to share


3 answers


In fact, I think this is not very good behavior for the application. I think you should disable (or hide) any actions that the user cannot perform. In case the user enters a URL or uses a bookmark from the moment they have privilege, show an error message instead of redirecting the login page.

Imagine that you are a user who has signed up for your application. You click on a UI element and it looks like you are logged out. There is no way for you to know that you shouldn't use it. Disabling / hiding an item prevents this scenario for most users. Redirecting to an error provides valuable feedback to the user on why the actions taken did not produce the expected results.



I am using a custom attribute derived from the AuthorizeAttribute to achieve this effect. If the user is not logged in, they are redirected to the login page. If they are logged in but not sufficiently privileged, a corresponding error view is displayed.

+1


a source


This already exists in ASP.NET MVC with the Authorize attribute:

[Authorize(Roles="Administrators")]
public AcitonResult ManageUsers() {

 return View();

}

      

Or



[Authorize(Users="Admin,SomeUser")]
public AcitonResult ManageUsers() {

   return View();

}

      

More information:
http://www.asp.net/learn/mvc/tutorial-17-vb.aspx

+1


a source


[Authorize(Roles = "Admin")]
public ActionResult ManageUsersController()
{
    ...
}

      

In your check web.config:

...
<forms loginUrl="~/your_login_page" defaultUrl="~/">
...

      

Also you have to set both MembershipProvider and RoleProvider in your web.config

+1


a source







All Articles