Skip to main content

Asp.Net Forms Authentication with Groups and Roles

I found this great post from Rob Convery on creating a FilterAttribute that can be used to authorize specific controller actions against roles. I’d always wanted to implement a Group strategy and had made several attempts. They all seemed like kluges and I was never really happy.

One small change to Rob’s code and I can do grouping in a simple manner. Note: If you have a large number of roles and groups, this will probably not work for you. Also, this uses Asp.Net MVC.

ok, Rob’s code basically checked for a single role and you could use a constant to supply the role name. Something like

[RequiresRoleAttribute(RoleToCheckFor = ApplicationRoles.AdminRole)]
public ActionResult Edit(int id)

My change just allows you to pass more than one role into RoleToCheckFor.  Basically, I split RoleToCheckFor using a comma.

[RequiresRoleAttribute(RoleToCheckFor = ApplicationRoles.ChangeClientsGroup)]
public ActionResult Edit(int id)
The ApplicationRoles class looks like this.
public class ApplicationRoles
public const string AdminRole = "Admin";
public const string EntryRole = "Entry";
public const string ManagementRole = "Management";
public const string SecurityRole = "Security";

public const string ChangeClientsGroup = Admin + "," + Entry;

ChangeClientsGroup is simply a constant that contains all the allowed roles for changing clients. Biggest drawback here, I want to change a group, I need to redeploy. This isn’t really a problem since I don’t have to change my roles a lot but…
public class RequiresRoleAttribute : ActionFilterAttribute
public string RoleToCheckFor { get; set; }

public override void OnActionExecuting(ActionExecutingContext filterContext)
//redirect if the user is not authenticated
if (!String.IsNullOrEmpty(RoleToCheckFor))

if (!filterContext.HttpContext.User.Identity.IsAuthenticated)

//use the current url for the redirect
string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;

//send them off to the login page
string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
filterContext.HttpContext.Response.Redirect(loginUrl, true);

bool isAuthorized = false;
string[] roles = this.RoleToCheckFor.Replace(" ", string.Empty).Split(',');
foreach (string role in roles)
isAuthorized = filterContext.HttpContext.User.IsInRole(role);
if (isAuthorized) { break; }
if (!isAuthorized)
ApplicationError appEevent = new ApplicationError();
appEevent.Caller = Thread.CurrentPrincipal.Identity.Name + ":" + filterContext.Controller.GetType().Name + ":" + filterContext.HttpContext.Request.Path;
appEevent.ErrorMessage = "Unauthorized access attempt";
filterContext.HttpContext.Response.Redirect("/SecurityViolation.htm", true);
throw new InvalidOperationException("No Role Specified");

Hopes this works for you!


Popular posts from this blog

Migrating Legacy Apps to the New SimpleMembership Provider

Asp.Net MVC4 uses the new SimpleMembership provider, changes the table structure and adds a new hashing algorithm. The reasons for the changes can be found in this article by Jon Galloway. This article shows how to migrate your existing apps to the new provider.I’m assuming that you stored your passwords in the unrecoverable SHA-1 format. If you didn’t, then you’ll have to change a couple of things. All of my apps are done this way so… I’m also assuming that you have created the basic skeleton of the new app and ran it once so the correct tables will be created.First, we’ll look at the new tables. Previously, we had all of those aspnet_xxxxxx tables. Here’s the new ones.UserProfileContains all of the elements relevant to the user. This is a combination of the aspnet_Users table and the aspnet_Profiles table.webpages_MembershipStores the password info when not using OAuth, Live, Facebook, etc. This table is somewhat of a match to the aspnet_Membership table.webpages_OAuthMembershipStor…

JavaScript function to automatically add slashes to date

In converting an old Windows app to a browser app, the user wanted to be able to enter dates without the slashes. Here's a simple jscript: 1:// Function to convert short date string (MMddyy) 2:// or (MMddyyyy) to a date string (mm/dd/yyyy). 3:// txtBox is the actual textbox control 4:// with the value to be processed. 5:function FixShortDate(txtBox) { 6:if (txtBox == null) { 7:return'' } 8: 9:var re = new RegExp(/(\d{6})(\d{2})?/); 10: 11:if (re.test(txtBox.value)) 12: { 13:if (txtBox.value.length == 8) { 14: txtBox.value = txtBox.value.substring(0, 2) + '/' + txtBox.value.substring(2, 4) + '/' + txtBox.value.substring(4, 8) 15: } 16: 17:if (txtBox.value.length == 6) { 18:if (txtBox.value.substring(4, 6) < 20)

Get Asp.Net Profile properties from Sql

Ever wanted to include the profile information from an Asp.Net profile in a query? It’s not that hard once you understand the structure. I’ve written a little function that does all the work. Note: I’m using Sql Server as my repository.

First we need to understand how the profile data is stored. Looking at the aspnet_Profile table, we can see that it stores the information in two columns: PropertyNames and PropertyValuesString.

Looking at PropertyNames we can see that it has a basic structure of Property Name, Data Type, Starting Position and Length. For example, in the string “FirstName:S:0:4:Phone:S:4:10:LastName:S:14:5:” we can see that FirstName is of type string, starts at position 0 and has a length of 4. Notice the zero base for the starting position, we need to correct for that in our function. This means in the PropertyValuesString “John2175551212Smith”, we would start with the first position and proceed 4 characters to get the name.

You might be thinking …