自定义授权属性

40

我正在构建自己的会员系统,不想使用 MS Membership 提供程序。我在互联网上和 StackOverflow 上搜索过,但找到的所有成果都是基于 MS Membership 提供程序构建的会员提供程序。

无论如何,我现在已经几乎将所有内容连接起来了,但我想使用一个自定义的授权属性,该属性利用了我的会员基础结构。我查看了站点上的线程,并尝试做类似的事情,但我不确定那是否是我需要的。到目前为止,这些是我拥有的类:

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;
    }
}

SharweAuthorizeAttribute: (我不确定我是否应该这样做)

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

现在我需要的是:

  1. 我的SharweAuthorizeAttribute类是否正确?
  2. 我需要能够将未经身份验证的用户重定向到登录页面。
  3. 我需要根据用户的角色(使用自己的角色提供程序)进行授权,所以我会做一些像这样的事情:

[SharweAuthorize(Roles="MyRole")]

就这些了。欢迎提出任何建议 :)

更新: 好的,我重新阅读了那个页面并找到了第二个问题的解决方案:

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);
}

如果我理解正确,请告诉我...


我知道这个问题有点老了,但是你如何在静态类上实现一个接口?7年前是否允许这样做? - Chris
1个回答

21

是的,你理解得没错(在我看来,实现一个自定义的成员资格提供程序更安全、更简单,但这是你的选择)

  1. 是的,正确的
  2. 你做对了
  3. 你从AuthorizeAttribute基类继承了roles属性,并在你的实现中检查用户是否在该角色中。

编辑:关于角色方面的更多信息

如果你有

[SharweAuthorize(Roles="MyRole")]

那么您可以在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;
}

谢谢您的回复。但是,您能否详细说明第三点呢?我不确定我理解了您的意思。一个小例子将非常感激 :) - Kassem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接