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

标签 c# asp.net asp.net-mvc-3 authorization

在 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/

    相关文章:

    c# - 如何在 C# 中验证 PowerShell 脚本语法?

    jquery - Uncaught Error : Dropzone already attached

    asp.net - GridView 数据绑定(bind)不起作用

    asp.net-mvc - 当页面依赖于 session 时,处理永久链接的正确方法是什么?

    css - 如何在mvc3中动态改变主题

    c# - 已具有此连接的打开的 DataReader

    c# - 以 window 8/10 技术无延迟地完全实时截屏

    c# - 在 ActionBlock 中收集结果时阻止收集

    c# - 在代码隐藏中设置其 url 时无法呈现图像

    ASP.NET MVC,帐户模型 : How to make relations to it?