且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

asp.net mvc的[授权()]属性混合组和用户

更新时间:2023-10-07 10:57:28

您可以亚型 AuthorizeAttribute 来看看用户的的角色。把我的头顶部(未经测试):

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(',');
            }
        }
    }
}