简体   繁体   English

如何在 RequireAssersion 中访问 HttpContext 和 Request?

[英]How to access HttpContext and Request in RequireAssersion?

I'm trying to create a custom authorization policy.我正在尝试创建自定义授权策略。 Let's say I want the URL to contain a token.假设我希望 URL 包含一个令牌。 For example:例如:

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

I want to show the list of customer to the user, only if:我想向用户显示客户列表,仅在以下情况下:

  1. URL has a token query string URL 有令牌查询字符串
  2. token is valid令牌有效

I tried this:我试过这个:

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

But I don't see how can I access HttpContext or the Request object from inside the policy.RequireAssertion .但是我看不到如何从 policy.RequireAssertion 内部访问 HttpContext 或 Request policy.RequireAssertion

How can I implement this?我该如何实施?

You can create a custom Authorization Handler, and in this handler get the token parameter from the Query string, and valid the joken.您可以创建一个自定义授权处理程序,并在此处理程序中从查询字符串中获取令牌参数,并验证笑话。 Refer the following steps:请参考以下步骤:

  1. Create a JwtTokenRequirement class: here we can set the query string parameter key value.创建一个JwtTokenRequirement class:这里我们可以设置查询字符串参数键值。 then in the handler method, we could according to it to find the token.然后在handler方法中,我们可以根据它找到token。

     //required using Microsoft.AspNetCore.Authorization; public class JwtTokenRequirement: IAuthorizationRequirement { public JwtTokenRequirement(string tokenname) { TokenName = tokenname; } public string TokenName { get; set; } }
  2. Create the JWTTokenHandler:创建 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. Add the following code to the ConfigureServices method:将以下代码添加到 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. Apply the Authorize attribute on the API action method:在 API 操作方法上应用 Authorize 属性:

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

Then the result is like this:然后结果是这样的:

在此处输入图像描述

Since the question was specifically about RequireAssertion , which takes a Func, which receives an AuthorizationHandlerContext , the answer is that the HttpContext is the AuthorizationHandlerContext's Resource.由于这个问题是专门关于RequireAssertion的,它接受一个 Func,它接收一个AuthorizationHandlerContext ,答案是 HttpContext 是 AuthorizationHandlerContext 的资源。 To use OP's code:要使用 OP 的代码:

services.AddAuthorization(options =>
{
    options.AddPolicy("IsPaydar", policy
        => policy.RequireAssertion(x => (x.Resource as HttpContext)?.Request?.Query["token"] == "myCoolToken")
});

Whether the Resource property really contains the HttpContext is up to the framework, so Zhi Lv's solution is certainly going to be more robust and you should probably use it anyway if your validation logic exceeds one line. Resource 属性是否真的包含 HttpContext 取决于框架,因此,Zhi Lv 的解决方案肯定会更加健壮,如果您的验证逻辑超过一行,您可能还是应该使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM