views:

306

answers:

3

In C# with MVC, i want to write a common utility or class in which if a particular conditoin fails need to redirect to login page.

For ex.: When the user logged in to the website, userid will be added to session. To Access the "ManageUsers" page, the user should be logged in as admin, else i need to redirect to Login page. i need to check this condition in some of the other similar pages also. i dont want to check either the user is admin or normal user while login. i need to check this in common class.

Any suggesstions?

+1  A: 

This already exist 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 infos:
http://www.asp.net/learn/mvc/tutorial-17-vb.aspx

Marwan Aouida
I have to check a condition in the common class based on the controller and action (i.e. Page) and redirect the user to Login.Its not only the role based check. I have to check some more conditions too, like string equal check(UserName == "Prasad").
Prasad
+1  A: 
[Authorize(Roles = "Admin")]
public ActionResult ManageUsersController()
{
    ...
}

In your web.config check:

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

Also you should setup both MembershipProvider and RoleProvider in your web.config

eu-ge-ne
+2  A: 

Actually I think this is not particularly good behavior for an application. I think you ought to disable (or hide) any actions that a user is not able to perform. In the case where the user hand-enters a URL, or uses a bookmark from when they had the privilege, show an error message rather than redirecting to the login page.

Imagine you're a user who is logged into your application. You click on a user interface element and it looks like you've been logged out. You have no way of knowing that you weren't supposed to use it. Disabling/hiding the element prevents this scenario from occurring for most users. Redirecting to an error gives valuable feedback to the user as to why the action they took did not result in what they expected.

I use a custom attribute derived from AuthorizeAttribute to achieve this effect. If a user isn't logged in, it redirects to the login page. If they are logged in, but not sufficiently privileged, it displays a suitable error view.

tvanfosson