我正在开发 MVC 应用程序并将 ASP.NET 身份用于用户角色。我重写了 AuthorizeAttribute 类的 3 个函数:
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!"); }
}
现在我的 Controller 授权如下:
[CustomAuthorize(Roles="Delete COA")]
即使在 dbo.AspNetRoles 表中我没有为名称为“Delete COA”的当前用户分配任何角色,我的代码也会为它授权当前用户。但是由于我的 CustomeAuthorizeAttribute 类没有从 Controller 获取角色属性的名称,我无法根据当前用户的角色进行过滤。
代替构造函数代码
this.allowedroles = roles;
获取字符串为:
roles = {string[0]}
但我需要这里的角色名称。这里有什么问题?
最佳答案
看来您正在使用属性作为参数。由于 AuthorizeAttribute
已经具有 Role
属性,您可以简单地使用它。
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
}
}
然后您可以申请任何操作:
[CustomAuthorize(Roles="Delete COA")]
public ActionResoult MyFancyAction(){}
或者对于多个角色,您可以:
[CustomAuthorize(Roles="FirstRole,SecondRole,AndSoOn")]
public ActionResoult MyFancyAction(){}
关于c# - 如何从 Controller 获取角色名称到 Custom AuthorizeAttribute 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31875735/