Reputation: 1336
I am developing MVC application and using ASP.NET identity for User Roles. I have override 3 functions of AuthorizeAttribute class as:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
private ApplicationDbContext context = new ApplicationDbContext();
private readonly string[] allowedroles;
public CustomAuthorizeAttribute(params string[] roles)
{ this.allowedroles = roles; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
string usr = httpContext.User.Identity.Name;
var userId = context.Users.Where(item => item.UserName == usr).Single().Id;
var uroles = context.Roles.ToList();
bool authorize = false;
foreach (var role in uroles)
{
var user = context.Users.Where(u => u.Roles.Any(r => r.RoleId == role.Id)).ToList();
if (user.Count() > 0)
{ authorize = true; }
}
return authorize;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{ filterContext.Result = new HttpUnauthorizedResult("Access is Denied!"); }
}
Now my controller Authorization is as:
[CustomAuthorize(Roles="Delete COA")]
And my code authorize the current user for it even then when in the dbo.AspNetRoles tables I have no role assigned to the current user with the name "Delete COA". But since my CustomeAuthorizeAttribute Class is not getting the name of the role attribute from the controller I am unable to filter as per the roles of the current User.
Instead the constructor code
this.allowedroles = roles;
gets the string as:
roles = {string[0]}
but I need the name of the role here. What is wrong here?
Upvotes: 2
Views: 3100
Reputation: 14741
It seems you are using property as a parameter. Since AuthorizeAttribute
already have had Role
property you could simply use it.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
private ApplicationDbContext context = new ApplicationDbContext();
// you don't need the constrictor and private roles field
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// spiting different roles by ','
var roles=this.Rols.Split(',');
// rest of your code
}
}
And you could apply to any action then:
[CustomAuthorize(Roles="Delete COA")]
public ActionResoult MyFancyAction(){}
Or for multiple role you could:
[CustomAuthorize(Roles="FirstRole,SecondRole,AndSoOn")]
public ActionResoult MyFancyAction(){}
Upvotes: 4