Here is an example of what I did
step 1 - creating the claims for user
var identity = new ClaimsIdentity(
new[] {
new Claim(ClaimTypes.Name, usr.Name),
new Claim(ClaimTypes.Email, usr.Email),
new Claim(ClaimTypes.Role, usr.Roles.FirstOrDefault().Role),
new Claim("StuffXId", usr.StuffXId + ""),
new Claim("StuffYId", usr.StuffYId + "")
}
, "BMMC"//"ApplicationCookie"
);
foreach(AccessLevels x in usr.AccessLevels)
identity.AddClaim(new Claim("AccessLevel", x.Access));
step 2 - I created my class BMClaimsAuthorize
public class BMClaimsAuthorize : AuthorizeAttribute
{
public string ClaimType { get; set; }
public string Value { get; set; }
public BMClaimsAuthorize() { }
public BMClaimsAuthorize(string ClaimType, string Value)
{
this.ClaimType = ClaimType;
this.Value = Value;
}
protected override bool AuthorizeCore(HttpContextBase context)
{
return context.User.Identity.IsAuthenticated
&& context.User.Identity is ClaimsIdentity
&& ((ClaimsIdentity)context.User.Identity).HasClaim(x =>
x.Type == ClaimType && x.Value == Value);
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult)
filterContext.Result = new RedirectResult("~/Account/DeniedAccess");
}
}
3 - using peject.BMTools (imported my library)
[BMClaimsAuthorize("AccessLevel", "General")]
public ActionResult Index()
{
ViewBag.Name = CurrentUser.Name;
ViewBag.Email = CurrentUser.Email;
ViewBag.StuffX = CurrentUser.ValueOf("StuffXId");
return View();
}
I created my own cotroller class (which inherits from controller) that helps me get the user claims easily
CurrentUser.Name
but that is another subject..
That is my actual code, I have 2 tables where users are mapped to a role and acceslevels
Role only tell if they are admins or not (kept as a table instead an user field in case I later on need multiple roles), they are on the top of controller clases where only adminds can access.
AccessLevel tell everything else (they filter by method). If you need something more complex, you can add more claims (as my AccessLevel claim) and edit the BMClaimsAuthorize and the AuthorizeCore method to meet your criteria.
For example make it accept an array of strings, so you send something like this
[BMClaimsAuthorize("AccessLevel", {"General","Admin","other"...})]
Hope this helps!