【问题标题】:Custom Authorize Attribute自定义授权属性
【发布时间】:2011-07-01 12:25:37
【问题描述】:

我正在构建自己的会员系统,我不想与 MS 会员提供者有任何关系。我浏览了互联网和 StackOverflow,但我能找到的只是建立在 MS Membership 提供者之上的成员提供者。

不管怎样,我现在几乎把所有东西都连接起来了,但我想使用一个自定义的 Authorize 属性,它利用了我的会员基础结构。我在网站上查看了this 线程,我正在尝试做类似的事情,但我不确定这是否是我需要的安静。到目前为止,这些是我上过的课程:

会话管理器:

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 年前允许的吗?

标签: asp.net-mvc asp.net-mvc-3 asp.net-membership


【解决方案1】:

是的,你没看错(IMO 实施自定义会员提供程序更安全、更简单,但这是你的选择)

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

【讨论】:

  • 感谢您的回复。但是你能扩展第三点吗?我不确定我明白你所说的。一个小例子将不胜感激:)
猜你喜欢
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-28
  • 1970-01-01
相关资源
最近更新 更多