gpt4 book ai didi

c# - Asp.Net MVC 5 - 自定义授权不起作用?

转载 作者:行者123 更新时间:2023-11-30 17:29:27 24 4
gpt4 key购买 nike

我有以下具有自定义授权属性的 Controller :

[CustomAuthorize(Roles = "Editor, Admin")]
public ActionResult Test()
{
//...

}

这是我的自定义授权码:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{

private readonly string[] _allowedRoles;

public CustomAuthorizeAttribute(params string[] roles)
{
_allowedRoles = roles;

}

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
throw new ArgumentNullException("httpContext");


var user = httpContext.User;

if (!user.Identity.IsAuthenticated)
{
return false;
}

if (_allowedRoles.Length > 0 && !_allowedRoles.Any(user.IsInRole))
{
return false;
}


return true;

}


}

自定义授权是否为不是编辑或管理员的用户返回true

我认为问题是这样的:

[CustomAuthorize(Roles = "Editor, Admin")]

我将它作为字符串传递,我需要在我的 CustomAuthorize 方法中将它转换为数组???

最佳答案

该属性的当前定义没有引用 Roles 属性,也没有填充 _allowedRoles 字段。

这就是为什么您的属性总是返回 true 的原因。

回顾自定义属性的重构逻辑

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute {
private readonly string[] _allowedRoles;

public CustomAuthorizeAttribute(params string[] roles) {
_allowedRoles = roles;
}

protected override bool AuthorizeCore(HttpContextBase httpContext) {
if (httpContext == null)
throw new ArgumentNullException("httpContext");

var user = httpContext.User;
if (user?.Identity?.IsAuthenticated) {
if (isInRole(user, _allowedRoles)) {
return true;
}
if (!string.IsNullOrWhiteSpace(Roles)) {
var roles = Roles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (isInRole(user, roles))
return true;
}
return true;
}
return false;
}

bool isInRole(IPrincipal user, string[] roles) {
return roles.Length > 0 && roles.Any(user.IsInRole);
}
}

可以这样用

[CustomAuthorize(Roles = "Editor, Admin")]
public ActionResult Test() {
//...
}

将根据用户拆分和检查角色的位置

或者喜欢

[CustomAuthorize("Editor", "Admin")]
public ActionResult Test() {
//...
}

这将使用参数数组填充属性的构造函数

关于c# - Asp.Net MVC 5 - 自定义授权不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51152912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com