gpt4 book ai didi

asp.net-mvc - 自定义授权属性

转载 作者:行者123 更新时间:2023-12-03 02:40:26 25 4
gpt4 key购买 nike

我正在构建自己的成员(member)系统,我不想与 MS 成员(member)提供商有任何关系。我浏览过互联网和 StackOverflow,但我所能找到的只是建立在 MS 成员(member)资格提供程序之上的成员(member)资格提供程序。

无论如何,我现在几乎已经把所有东西都连接起来了,但我想使用一个利用我的成员(member)基础设施的自定义授权属性。我查看了this网站上的线程,我正在尝试做类似的事情,但我不确定这是否是我需要的安静。到目前为止,这些是我已经掌握的类(class):

session 管理器:

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

如果我做对了请告诉我...

最佳答案

是的,您说得对(IMO,实现自定义成员(member)资格提供商更安全、更简单,但这是您的选择)

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

关于asp.net-mvc - 自定义授权属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5070339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com