你如何在C#中进行访问控制?

时间:2009-11-12 21:59:12

标签: c# acl

如何在C#中进行业务逻辑级访问控制?我昨晚开始修改一个简单的系统,它存在于LINQ对象中,但我意识到我从未见过一个特别干净的访问控制系统。我想知道大师是怎么做的,看看你是否发现了我深夜玩具上的任何漏洞。

我觉得我正在跳过一些不必要的箍,以便构建一个灵活的只读访问控制对象,它似乎应该有一些我不知道的框架预构建的小部件。

#region Simple Demo
public class SomeObject
{
    public AccessControl AccessControl;
    public SomeObject()
    {
        ConfigureAccessControl();
    }
    private void ConfigureAccessControl()
    {
        AccessControlBuilder acb = new AccessControlBuilder();
        acb.AddRole(UserTypes.Admin, true, true);
        acb.AddRole(UserTypes.Anonymous, true, true);
        acb.AddRole(UserTypes.Owner, true, true);
        acb.AddRole(UserTypes.User, true, true);
        AccessControl = acb.GetAccessControl();
    }
}

public class ObjectFactory
{
    private int _requestingUserId;
    public ObjectFactory(int RequestingUserId)
    {
        _requestingUserId = RequestingUserId;
    }

    public SomeObject GetSomeObject()
    {
        SomeObject sso = new SomeObject();
        if (sso.AccessControl.UserAllowed(_requestingUserId, UserActions.Read))
            return new SomeObject();
        else
            throw new Exception("Unauthorized Access");
    }
}
#endregion

#region AccessControl Code
public class AccessControl
{
    private Hashtable _data = new Hashtable();
    public AccessControl(Hashtable data)
    {
        _data = data;
    }
    public bool UserAllowed(int UserId, UserActions Action)
    {   //Assorted app-specific logic here to determine role.
        //Determine if User is Admin
        //Determine if User is Owner
        //Determine if User is Logged In
        //Determine if User is Anonymous
        //Check read/write for determined role
        return true;
    }
    protected AccessControlSettings Role(UserTypes ut)
    {
        return (AccessControlSettings)_data[ut];
    }
}
public class AccessControlBuilder
{
    private Hashtable _data = new Hashtable();
    public void AddRole(UserTypes ut, bool read, bool write)
    {
        _data.Add(ut, new AccessControlSettings(read, write));
    }
    public AccessControl GetAccessControl()
    {
        return new AccessControl(_data);
    }
}
public enum UserActions
{
    Read,
    Write
}
public enum UserTypes
{
    Admin,
    Owner,
    User,
    Anonymous
}
public class AccessControlSettings
{   //Wraps specific access options so we make them set once in the builder 
    public bool Read { get { return _read; } }
    public bool Write { get { return _write; } }
    private bool _read;
    private bool _write;
    public AccessControlSettings(bool read, bool write)
    {
        _read = read;
        _write = write;
    }
}
#endregion

0 个答案:

没有答案