【问题标题】:How to access HttpContext and Request in RequireAssersion?如何在 RequireAssersion 中访问 HttpContext 和 Request?
【发布时间】:2022-01-16 22:34:24
【问题描述】:

我正在尝试创建自定义授权策略。假设我希望 URL 包含一个令牌。例如:

https://example.com/customer/list?token=2nHxltsDOjThQJWufcGU1v36RdqYoBE9

我想向用户显示客户列表,前提是:

  1. URL 有一个令牌查询字符串
  2. 令牌有效

我试过这个:

services.AddAuthorization(options =>
{
    options.AddPolicy("IsPaydar", policy => policy.RequireAssertion(x => // stuck here))
});

但我看不到如何从 policy.RequireAssertion 内部访问 HttpContext 或 Request 对象。

我该如何实现?

【问题讨论】:

    标签: c# asp.net-core security


    【解决方案1】:

    您可以创建一个自定义的授权处理程序,并在此处理程序中从查询字符串中获取令牌参数,并验证笑话。参考以下步骤:

    1. 创建一个JwtTokenRequirement类:这里我们可以设置查询字符串参数键值。然后在handler方法中,我们可以根据它找到token。

       //required using Microsoft.AspNetCore.Authorization;
       public class JwtTokenRequirement : IAuthorizationRequirement
       {
           public JwtTokenRequirement(string  tokenname)
           {
               TokenName = tokenname;
           }
      
           public string TokenName { get; set; }
       }
      
    2. 创建 JWTTokenHandler:

       //required using Microsoft.AspNetCore.Authorization;
       //required using Microsoft.AspNetCore.Http;
       public class JWTTokenHandler : AuthorizationHandler<JwtTokenRequirement>
       {
           IHttpContextAccessor _httpContextAccessor = null;
      
           public JWTTokenHandler(IHttpContextAccessor httpContextAccessor)
           {
               _httpContextAccessor = httpContextAccessor;
           }
           protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, JwtTokenRequirement requirement)
           {
      
               HttpContext httpContext = _httpContextAccessor.HttpContext; // Access context here
      
               var token =  httpContext.Request.Query[requirement.TokenName].ToString();  //get the jwtkoken
      
               if (!string.IsNullOrEmpty(token))
               {
                   if (IsValidToken(token))
                   {
                       context.Succeed(requirement);
      
                   }
      
               }
               else
               {
                   context.Fail();
               } 
               return Task.FromResult(0);
           }
      
           public bool IsValidToken(string authToken)
           {
               //validate Token here  
               return true;
           }
       }
      
    3. 将以下代码添加到 ConfigureServices 方法中:

           services.AddHttpContextAccessor();
           services.AddAuthorization(options =>
           {
               options.AddPolicy("jwtpolicy",
                                 policy => policy.Requirements.Add(new JwtTokenRequirement("jwttoken"))); //configure the policy and set the parameter key value. in this sample the key is "jwttoken"
           });
           services.AddSingleton<IAuthorizationHandler, JWTTokenHandler>();
      
    4. 在 API 操作方法上应用 Authorize 属性:

       [Authorize(Policy = "jwtpolicy")]
       [HttpGet("{id}")] 
       public string Get(int id)
       {
           return "value";
       }
      

    那么结果是这样的:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-17
      • 2019-11-17
      • 2019-08-24
      • 2010-12-10
      • 2015-08-07
      • 2019-05-17
      • 2016-02-28
      • 1970-01-01
      相关资源
      最近更新 更多