gpt4 book ai didi

c# - 如果角色名称包含空格,则无法使 AuthorizeAttribute 工作

转载 作者:行者123 更新时间:2023-12-04 23:05:41 26 4
gpt4 key购买 nike

在 Windows 域内网站点(使用 <authentication mode="Windows" /> )上工作时,我遇到了以下问题:

[Authorize(Roles = "Domain Users, Domain Admins")]
public class MyController: Controller {...}

由于事件目录组名称中的空格,此 Controller 对任何用户都不可用。那么我可以让 MVC(或 ASP.Net)正确授权,同时使用带空格的角色名称(此处:AD 组的名称)吗?

只是类似的问题没有回应:
  • AD Groups with spaces used for roles authorization .
  • How to write AuthorizeAttribute if a role contains space
  • 最佳答案

    创建您自己的属性并从 AuthorizeAttribute 派生。然后覆盖 AuthorizeCore 方法并通过对包含空格的角色进行验证来实现您自己的逻辑。

    一个例子可能是这样的:

    public class CustomAuthAttribute : AuthorizeAttribute
    {
    private readonly IUserRoleService _userRoleService;
    private string[] _allowedRoles;

    public CustomAuthAttribute(params string[] roles)
    {
    _userRoleService = new UserRoleService();
    _allowedRoles = roles;
    }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
    //something like this.
    var userName = httpContext.User.Identity.Name;
    var userRoles = _userRoleService .GetUserRoles(userName); // return list of strings
    return _allowedRoles.Any(x => userRoles.Contains(x));
    }

    }

    用法
    [CustomAuth("role withspace","admin")]
    public ActionResult Index()
    {
    }

    关于c# - 如果角色名称包含空格,则无法使 AuthorizeAttribute 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13063001/

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