Pages

Using Authorize attribute in .NET MVC with custom authentication

Here is how you can use Authorize attribute in .NET MVC to authenticate and authorize user requests.

1. Open Global.asax file in editor and paste the folling code in it :-

 protected void Application_OnPostAuthenticateRequest(Object sender, EventArgs e)
 {
           if (Session["User"] != null)
           {
                   String[] userRoles = (String[])Session["UserRoles"];
                   String userName = (String)Session["UserName"];

                    //if the user is logged in set context
                    GenericIdentity userIdentity = new GenericIdentity(userName , "Forms");
                    GenericPrincipal userPrincipal = new GenericPrincipal(userIdentity, userRoles);
                    HttpContext.Current.User = userPrincipal;
           }
       
 }

The above code will set the context for the request which is used by Authorize attribute. In this code userRoles defines the roles current user have it is used by the Authorize attribute to check whether the user is authorized to access the resource or not.

2. Open web.config file and put the below code in <system.web> section under the <configuration> section.

<authentication mode="Forms">
      <forms loginUrl="~/Home/Index" />
 </authentication>

In this code the loginUrl is where the user is redirected if he/she is not logged-in.

3. All set to go, now go to the controller and put the Authorize attribute to work. Below code shows different ways of using Authorize.
a) Put Authorize attribute on individual action. 

public class AccountController : Controller { public AccountController () { . . . } [Authorize] public ActionResult Manage() { . . . } public ActionResult Register() { . . . }
public ActionResult LogOff() { . . . } . . . }
b) Put Authorize attribute on the controller itself. In this case the authorize will be 
applied to all the actions in the controller. Now if you want to allow access to an 
action without authentication then you need to apply the AllowAnonymous attribute on 
that action. 
[Authorize]
public class AccountController : Controller
{
    public AccountController () { . . . }
    
    [AllowAnonymous]
    public ActionResult Register() { . . . }

    public ActionResult Manage() { . . . }

    public ActionResult LogOff() { . . . }
    . . .
}


c) Provide roles along with Authorize attribute.
public class AccountController : Controller
{    
    [Authorize(Roles="Administrators")]
    public ActionResult Manage() { . . . }
    . . .
}

In the last example(i.e. example c) the user can access "Manage" Action only if the userRoles array for that user contains "Administrators".

No comments:

Post a Comment