尝试在ActionFilterAttribute中访问HttpContext

问题描述 投票:0回答:1

所以我试图访问 httpContext 访问器来获取 jwt 令牌声明,但是当我尝试获取自定义 authroize 类中的声明时,它的结果为空,并且其 IsAuthenticated 标志为 false

示例代码

public class Authorize : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        // Get role ID from claims
        if (!int.TryParse(actionContext.HttpContext.User?.FindFirstValue("AcmRoleId"), out int roleId))
        {
            actionContext.Result = new ContentResult
            {
                StatusCode = (int)HttpStatusCode.BadRequest,
                Content = "Role ID not found in token"
            };
            return;
        }
}

这就是我将如何使用它

[@Authorize(ModuleName = "Dashboard", Read = (int)ModulePrivileges.Own)]

我期望 HttpContext 包含 jwt 令牌声明,但不知道为什么它不包含任何声明,如果它们是替代方案,请告诉我

asp.net-core .net-core httpcontext claims
1个回答
0
投票

您需要为自定义授权属性实现

AuthorizeAttribute
IAuthorizationFilter
。比如下面这样:

public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    private readonly string _role;

    public CustomAuthorizeAttribute(string role)
    {
        _role = role;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.User;
        
        // Custom authorization logic
        if (!user.Identity.IsAuthenticated || !user.IsInRole(_role))
        {
            context.Result = new ForbidResult();
        }
    }
}

然后你可以使用

[CustomAuthorize("AcmRole")]

© www.soinside.com 2019 - 2024. All rights reserved.