[英]Authorize attribute for any roles
Let's say I have WebApi Controller 假设我有WebApi控制器
[Authorize]
public class SomeApiController : ApiController
Controller action methods itself does not have any [Authorize]
or [AllowAnonymous]
attributes. 控制器操作方法本身没有任何
[Authorize]
或[AllowAnonymous]
属性。
I want Authorize attribute to return 401 (Unauthorized) error if user has no roles - seems logical (if user had role and now doesn't have ANY - he shouldn't be allowed to perform action even though user is authenticated). 我希望Authorize属性在用户没有角色的情况下返回401(未经授权)错误-似乎合乎逻辑(如果用户具有角色并且现在没有ANY-即使已通过身份验证,也不应允许他执行操作)。 I have looked to asp.net mvc webstack I have found the following code in Authorize attribute:
我查看了asp.net mvc webstack,在Authorize属性中找到了以下代码:
if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))
{
return false;
}
So looks like if we didn't passed roles authorize attribute just checks if user is authenticated. 因此,看起来我们是否未通过角色授权属性,只是检查用户是否已通过身份验证。 Setting each role in Roles list is not an option for me ( I mean
[Authorize(Roles="role1,role2,...")]
). 在“角色”列表中设置每个角色对我来说不是一个选项(我的意思是
[Authorize(Roles="role1,role2,...")]
)。
Therefore question - can I somehow achieve setting Authorize attribute to check if user has ANY role. 因此,问题-我可以以某种方式实现设置Authorize属性来检查用户是否具有任何角色。 Or it's better to write custom attribute inherited from above?
还是最好编写从上面继承的自定义属性?
Create custom attribute like below: 创建如下的自定义属性:
public override void OnAuthorization(AuthorizationContext filterContext)
{
string[] userRoles = System.Web.Security.Roles.GetRolesForUser(filterContext.HttpContext.User.Identity.Name);
if (!userRoles.Any())
{
throw new HttpException(401, "Unauthorized");
}
base.HandleUnauthorizedRequest(filterContext);
}
} }
Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.