gpt4 book ai didi

asp.net-mvc - 自定义授权属性(后续)

转载 作者:行者123 更新时间:2023-12-03 16:11:17 27 4
gpt4 key购买 nike

好的跟进 this thread ,这就是我想出的……

public class SharweAuthorizeAttribute : AuthorizeAttribute
{
private bool isAuthenticated = false;
private bool isAuthorized = false;
public new string[] Roles { get; set; }

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (SessionManager.CheckSession(SessionKeys.User) == true)
{
isAuthenticated = true;
foreach (string role in Roles)
{
if (RolesService.HasRole((string)role))
isAuthorized = true;
}
}
return (isAuthenticated && isAuthorized);
}

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!isAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "User" },
{ "controller", "Login" }
});
} else if(!isAuthorized) {
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "Home" },
{ "controller", "Error" }
});
}
}
}

我是如何/为什么想出这个的?因为我相信 AuthorizeAttribute 工作流程如下:
  • 首先,AuthorizeCore 被触发。如果返回 true,则用户已获得授权。如果返回 false,则触发 HandleUnauthorizedRequest。那正确吗?
  • 我在某处读到我需要使用 new关键字来覆盖属性。因此,这就是我覆盖 Roles 属性的方式。但是,如果覆盖属性与初始属性(基类中的那个)属于不同类型,那是否也会隐藏它或创建一个完全不同的属性呢?

  • 所以你怎么看?这真的应该奏效吗?我现在无法测试,因为我还没有设置UI(等待设计师完成设计)...... 其实这是我第一次体会到TDD的好处,我以前认为它是彻头彻尾的愚蠢而无用,但我错了:)

    P.S:在 this thread ,@tvanfosson 正在设置上下文的 CachePolicy(我认为),有人可以解释一下,为什么我可能需要这样做吗?

    提前致谢。

    最佳答案

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
    private readonly bool _authorize;
    private readonly string[] _roles;

    public CustomAuthorizeAttribute(string roles)
    {
    _authorize = true;
    _roles = roles.Split(',');
    }

    public CustomAuthorizeAttribute(string roles, bool isAdminPath)
    {
    _authorize = true;
    _roles = roles.Split(',');
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
    //if controller have role auth and user is not loged
    if(_authorize && !httpContext.User.Identity.IsAuthenticated)
    return false;

    // if controller have role auth and user is loged
    if(_roles != null)
    {
    //grab user roles from DB
    var UserRole = RoleRepository.GetUserRole(new Guid(httpContext.User.Identity.Name));
    if (_roles.Contains(UserRole))
    return true;
    }
    return false;
    }
    }

    在 Controller 中
    [CustomAuthorize("Administrator,Company,OtherRole")]
    public ActionResult Test(){
    return View();
    }

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

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