自定义授权属性和实体框架

时间:2014-12-05 18:26:32

标签: c# asp.net-mvc entity-framework asp.net-mvc-5 authorize-attribute

我正在我的asp.net应用程序中实现基于Action / Activity的授权。我试图使它成为一个可重用的库,以便我可以将它用于其他项目。我正在使用实体框架进行数据访问。

我能够实现功能但不确定如何为Authorize属性配置Entity Framework连接字符串。

自定义授权属性:

public class AuthorizeAction: AuthorizeAttribute
{
    private string _actions;
    private string[] _actionsSplit = new string[0];

    public string Actions
    {
        get { return _actions ?? String.Empty; }
        set
        {
            _actions = value;
            _actionsSplit = value.Split(',');
        }
    }

    protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
    {
        string userid = string.Empty;

        if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }

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

        userid = user.Identity.Name;

        if(_actionsSplit.Length > 0)
        {
            AuthManager manager = new AuthManager();
            if (!manager.AuthorizeAction(_actionsSplit, userid)) //This will authorize the user against an action
                return false;
        }
        return true;
    }

我正在使用的AuthManager类有一个重载方法来接受配置文件的实体框架连接字符串名称,但我不确定这是如何配置或用户提供的。

AuthManager代码:

public class AuthManager
{
    private string connectionConfigName = "AuthorizationContext";

    public AuthManager() { }

    public AuthManager(string connectionName)
    {
        connectionConfigName = connectionName;
    }

    /// <summary>
    /// Authorizes the actions against userid supplied
    /// </summary>
    /// <param name="actionNames">Comma seperated list of action names</param>
    /// <param name="userAlias">Unique user identifier</param>
    /// <returns>True if user has access to atleast one of the actions supplies otherwise false</returns>
    public bool AuthorizeAction(string[] actions, string userAlias)
    {
        using (AuthorizationContext context = new AuthorizationContext(connectionConfigName))
        {
            //List<string> actions = actionNames.Split(',').ToList<string>();

            var count = (from ur in context.UserRoles
                         join ra in context.RoleActions on new { Key1 = ur.RoleId, Key2 = ur.UserAlias } equals new { Key1 = ra.RoleId, Key2 = userAlias}
                         join a in context.Actions on ra.ActionId equals a.ActionId
                         where actions.Contains(a.ActionName) && ra.Allow == true
                         select ur).Count();

            return (count > 0);
        }
    }
}

我查看了使用RoleProvider,但因为我不打算使用任何内置功能,不确定这是不是一个好主意。请帮忙。

0 个答案:

没有答案