Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding OnAuthorization in ASP.NET MVC in base controller

In my ASP.NET MVC application, I'm trying to figure out whether the user has access to a particular controller, restricted by the authorize data annotation as follows

[Authorize(Roles = "user")]

I'm attempting to override OnAuthorization in order to check:-

  • If the request is authenticated (which works great)
  • If the user is authorised to access the requested view (which doesn't work)

My user roles are stored in a SessionManager object I've created - SessionManager.ActiveUser.Roles

Here's what I have in the form of pseudo-code but if anybody could help me get this right, I'd really appreciate it.

public class HomeBaseController : Controller
{
    protected override void OnAuthorization(AuthorizationContext context)
    {
        if (context.HttpContext.User.Identity.IsAuthenticated)
        {
            // these values combined are our roleName 

            bool isAuthorised = context.HttpContext.User.IsInRole(context.RequestContext.HttpContext.User.Identity.); 


            if (!context.HttpContext.User.IsInRole(---the roles associated with the requested controller action (e.g. user)---))
            {
                var url = new UrlHelper(context.RequestContext);
                var logonUrl = url.Action("LogOn", "SSO", new { reason = "youAreAuthorisedButNotAllowedToViewThisPage" });
                context.Result = new RedirectResult(logonUrl);

                return;
            } 
        }
    }
like image 849
Nick Avatar asked Jun 27 '12 09:06

Nick


People also ask

How do you override OnAuthorization?

Right-click on the solution and add a new class. Enter the class name and click on Add. Next Inherite Attribute, IAuthorizationFilter to CustomAuthorization class which has overridden the OnAuthorization method. The OnAuthorization Method has the AuthorizationFilterContext parameter.

What is Custom authentication in MVC?

For building custom authentication, we use membership provider class which is able to check the user credentials (username & password) and role provider class that is used to verify the user authorization based on his/her roles.

What is authorization and authentication in MVC?

ASP.NET MVC Authentication is a feature in MVC that helps in making the website highly secure and safe. Authentication is the process of confirming or validating the user's identity if the user who is trying to access the web page or web application is a genuine user or not.


1 Answers

As far as overriding OnAuthorization according to ProASP.NET MVC3 Book they do not recommend overriding it since the default implementation of this method securely handles content cached using OutputCache Filter.

If you are looking for Custom Authentication (using Forms Auth) and Authorization (Using Role provider logic then below is how I secured my application.

EDIT: The following logic uses in-built forms authentication and roles manager. Once user is authenticated and authorized the User Identity can be used to check both the authentication (User.Identity.IsAuthenticated) and the roles User.IsInRole("admin")

In Web.Config:

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="15" slidingExpiration="true" enableCrossAppRedirects="false" protection="All" />
</authentication>
<roleManager enabled="true" defaultProvider="MyRolesProvider" cacheRolesInCookie="true" cookieProtection="All">
  <providers>
    <clear />
    <add name="MyRolesProvider" type="MyApp.Library.CustomRolesProvider" />
  </providers>
</roleManager>

For Role Authorization Extend RoleProvider and override methods as required.

public class CustomRolesProvider : RoleProvider
{
    public override string[] GetRolesForUser(string username)
    {
       // You need to return string of Roles Here which should match your role names which you plan to use.
       //Some Logic to fetch roles after checking if User is Authenticated...    

        return new string[] { "admin" , "editor" };
    }

    //Rest all of them I have kept not implemented as I did not need them...


}

In Your controller Now you can use this:

 [Authorize(Roles="Admin")]
    public class AdminController : Controller
    {
    ....

    }

For Authentication I have implemented my custom Authentication Check but I still use Forms Authentication:

//This one calls by Custom Authentication to validate username/password
public ActionResult LogOn(LogOnViewModel model, string returnUrl)
{
    if(Authenticate("test","test"))
    {
     .......
    }
}

public bool Authenticate(string username, string password)
{
   //Authentication Logic and Set the cookie if correct else false.
   //..... your logic....
   //.....

   FormsAuthentication.SetAuthCookie(username, false);
}
like image 135
bdoshi Avatar answered Sep 27 '22 22:09

bdoshi