简体   繁体   English

MVC使用静态设置类中的动态角色进行授权

[英]MVC Authorize with dynamic roles from static setting class

I'm currently developing an app that needs to be used by multiple customers, This means that i have to change the roles in my authorize tags between each publish of the application. 我目前正在开发一个需要由多个客户使用的应用程序,这意味着我必须在每次应用程序发布之间更改我的授权标签中的角色。

Currently I'm storing customer specific data in a static settings class 目前,我正在静态设置类中存储客户特定的数据

public abstract class Settings
{
    public virtual string ConnectionString { get; internal set; } = "";
    public virtual string SharepointMail { get; internal set; } = "";
    public virtual string SharepointPassword { get; internal set; } = "";
    public virtual string SharepointSite { get; internal set; } = "";
    public virtual string SharepointDocumentLibrary { get; internal set; } = "";
    public virtual int ProjectId { get; internal set; }
    public virtual string SuperUserRole { get; internal set; }
    public virtual string UserRole { get; internal set; } = "";
    public virtual string ContributorRole { get; internal set; } = "";


    private static Settings _instance;
    public static Settings Instance
    {
        get
        {
            if (_instance != null)
                return _instance;

  #if DEBUG
            return _instance = new DebugSettings();
  #elif TCOTEST
            return _instance = new TcoTestSettings();
  #elif TCORELEASE
            return _instance = new TcoReleaseSettings();
  #endif
        }
    }
}

I would like to be able to set the superuserrole for each configuration, but the property needs to be constant to be used as an authorize attribute. 我希望能够为每个配置设置超级用户角色,但是该属性需要保持恒定才能用作授权属性。

How do i go about this? 我该怎么办?

I ended up creating a custom authorize attribute 我最终创建了一个自定义授权属性

public class AuthorizeRoleAttribute : AuthorizeAttribute
{
    public string AccessRole { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {
            return false;
        }
        switch (AccessRole)
        {
            case "SuperUser":
                return httpContext.User.IsInRole(Settings.Instance.SuperUserRole);
            case "User":
                return httpContext.User.IsInRole(Settings.Instance.UserRole) || httpContext.User.IsInRole(Settings.Instance.SuperUserRole);
            case "Any":
                return httpContext.User.IsInRole(Settings.Instance.ContributorRole) || httpContext.User.IsInRole(Settings.Instance.UserRole) || httpContext.User.IsInRole(Settings.Instance.SuperUserRole);
            default:
                return false;
        }
    }
}

Which i can then use like this: 然后我可以这样使用:

[AuthorizeRole(AccessRole = "Any")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM