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:-
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;
}
}
}
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With