Yes, you can do some custom autorization with the Forms Authentication but you will need to do some customizations.
First of all, you have to customize your AuthenticateRequest event of your application to work with roles, so, on your Global.asax you have to set a code to customize it to the current user:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
if (HttpContext.Current.User.Identity.IsAuthenticated)
if (HttpContext.Current.User.Identity is FormsIdentity)
{
var id = (FormsIdentity)HttpContext.Current.User.Identity;
var ticket = id.Ticket;
// Get the stored user-data, in this case, our roles
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
When you authenticate the user you have to set the role, so on your controller you have to have a post action to authentication with a code like this:
if (LoginService.Validate(userame, password)
{
FormsAuthentication.Initialize();
var ticket = new FormsAuthenticationTicket(1,
username, //user
DateTime.Now, //begin
DateTime.Now.AddHours(3), //timeout
false, //remember?
permission, // permission.. "admin" or for more than one "admin,marketing,sales"
FormsAuthentication.FormsCookiePath);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
HttpContext.Current.Response.Cookies.Add(cookie);
}
After that, you will be able to use a code like your post:
if (User.IsInRole("Admin"))
{ /** do something / }
Or
if (User.IsInRole("Admin") || (User.IsInRole("Marketing") && User.IsInRole("Sales")))
{ /** do something / }
You also can check the role on the Authorize attribute of asp.net mvc:
[Authorize(Roles = "Admin")]
public class CompanyController : Controller
{
// actions
}
Edits
You could have a table to associate a permission "Admin" with some privileges (edit comments, delete comments, etc... that could be stored in a table on database). Try something like this to implement a custom check permission:
public static class UserExtension
{
private static bool RoleHasPrivilege(string role, int privilege)
{
// performe a database/cache access to check if the role has the privilege
}
public static bool IsInRole(this IPrincipal user, string role, int privilege)
{
// check if the user authenticate has the "role" permission and the privilege is associate with this role...
return user.IsInRole(role) && RoleHasPrivilege(role, privilege);
}
}
And you could use:
if (User.IsInRole("Admin", 1))
{
// "Admins" has access
// 1 - can edit posts... for sample
}