自定义授权属性

Kas*_*sem 40 asp.net-mvc asp.net-membership asp.net-mvc-3

我正在构建自己的会员系统,我想要与MS会员提供商无关.我查看了互联网和StackOverflow,但我所能找到的只是建立在MS会员提供商之上的会员提供商.

无论如何,我现在几乎所有东西都挂了,但我想使用自定义的Authorize属性来利用我的会员基础设施.我在网站上查看了这个帖子,我正在尝试做类似的事情,但我不确定我需要的是什么.到目前为止,这些是我得到的课程:

SessionManager:

public static class SessionManager : ISessionManager
{
    public static void RegisterSession(string key, object obj)
    {
        System.Web.HttpContext.Current.Session[key] = obj;
    }

    public static void FreeSession(string key)
    {
        System.Web.HttpContext.Current.Session[key] = null;
    }


    public static bool CheckSession(string key)
    {
        if (System.Web.HttpContext.Current.Session[key] != null)
            return true;
        else
            return false;
    }


    public static object ReturnSessionObject(string key)
    {
        if (CheckSession(key))
            return System.Web.HttpContext.Current.Session[key];
        else
            return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

SharweAuthorizeAttribute: (我真的不知道,如果这确实是我应该做的事)

public class SharweAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (SessionManager.CheckSession(SessionKeys.User) == true)
            return true;
        else 
            return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在这就是我需要的:

  1. 我的SharweAuthorizeAttribute类首先是正确的吗?
  2. 我需要能够将未经身份验证的用户重定向到登录页面
  3. 我需要根据用户的角色授权用户(使用我自己的角色提供者),所以我会做类似的事情:

    [SharweAuthorize(Roles="MyRole")]
    
    Run Code Online (Sandbox Code Playgroud)

这就是我猜...任何建议都非常欢迎:)

更新: 好的我再次阅读该页面,找到了问题二的解决方案:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    if (SessionManager.CheckSession(SessionKeys.User) == false)
    {
        filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary 
                        {
                            { "action", "ActionName" },
                            { "controller", "ControllerName" }
                        });
    }
    else
        base.HandleUnauthorizedRequest(filterContext);
}
Run Code Online (Sandbox Code Playgroud)

如果我做得对,请告诉我...

Edu*_*eni 21

是的,你做得对(IMO实现自定义会员提供商更安全,更简单,但这是你的选择)

  1. 是的,这是对的
  2. 你做得对
  3. rolesAuthorizeAttribute基类继承该属性,并在用户担任角色时检入您的实现.

编辑:更多关于角色的事情

如果你有

[SharweAuthorize(Roles="MyRole")]
Run Code Online (Sandbox Code Playgroud)

然后,您可以检查AuthorizeCore方法中的Roles属性

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    if (SessionManager.CheckSession(SessionKeys.User) == true) {
        if (SessionManager.CheckUserIsInRole( Roles )) // where Roles == "MyRole"
           return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)