asp.net mvc [Authorize()] attribute for mixed group and user

烈酒焚心 提交于 2019-11-29 07:34:41
Craig Stuntz

You can subtype AuthorizeAttribute to look at Users and Roles. off the top of my head (untested):

using System;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    // This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.
    protected override bool AuthorizeCore(HttpContextBase httpContext) {
        base.AuthorizeCore(httpContext);

        if ((!string.IsNullOrEmpty(Users) && (_usersSplit.Length == 0)) ||
           (!string.IsNullOrEmpty(Roles) && (_rolesSplit.Length == 0)))
        {
            // wish base._usersSplit were protected instead of private...
            InitializeSplits();                
        }

        IPrincipal user = httpContext.User;
        if (!user.Identity.IsAuthenticated) {
            return false;
        }

        var userRequired = _usersSplit.Length > 0;
        var userValid = userRequired
            && _usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase);

        var roleRequired = _rolesSplit.Length > 0;
        var roleValid = (roleRequired) 
            && _rolesSplit.Any(user.IsInRole);

        var userOrRoleRequired = userRequired || roleRequired;

        return (!userOrRoleRequired) || userValid || roleValid;
    }

    private string[] _rolesSplit = new string[0];
    private string[] _usersSplit = new string[0];

    private void InitializeSplits()
    {
        lock(this)
        {
            if ((_rolesSplit.Length == 0) || (_usersSplit.Length == 0))
            {
                _rolesSplit = Roles.Split(',');
                _usersSplit = Users.Split(',');
            }
        }
    }
}

As you are prefixing your domain/user and domain/group strings with the '@' character you do not need to double escape the backslash. You could try replacing these lines with either:

[Authorize(Roles="MyDomain\\company.security.group.name")]  
[Authorize(Users="MyDoamin\\MyName")]

or

[Authorize(Roles=@"MyDomain\company.security.group.name")]  
[Authorize(Users=@"MyDoamin\MyName")]

A bit of further reading has also revealed that the Authorize filter will perform a 'users' and 'roles' check. If the user doesn't meet both requirements then they will be refused access.
To get the behaviour you want you will need to write a custom authorisation filter as suggested in a previous answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!