【问题标题】:How to have custom validation of a JWT bearer token early in the pipeline如何在管道早期对 JWT 不记名令牌进行自定义验证
【发布时间】:2018-11-16 09:11:25
【问题描述】:

我的传入不记名令牌的受众不正确。令牌中有足够的信息通过其他声明证明受众应该是什么。 我希望尽早修复它,以便我仍然可以利用 JwtBearerOptions.TokenValidationParameters.ValidateAudience = true; JwtBearerOptions.TokenValidationParameters.ValidAudiences ={"右边那个"};

我可以挂钩 OnTokenValidated 事件,并重写主体,但为时已晚。在管道的早期,令牌已经过验证,由于受众错误,它已经被拒绝。

我可以通过使用授权策略、设置 ValidateAudience=false 并在控制器级别处理此问题来解决此问题。我不喜欢必须将 [Authorize("the-correct-audience")] 属性添加到每个控制器,因为有人会错过一个。

另一种选择是引入一个新的中间件,该中间件适用于 identitiy.claims 并在此处拒绝。

最后,我希望能够像 validateAudience = true 完成的那样全局拒绝这些令牌,当 validateAudience 作为过滤选项从我身边拿走时。

有没有人做过类似的事情,你还用过哪些其他替代方法?

【问题讨论】:

    标签: asp.net-core-2.0 asp.net-authorization


    【解决方案1】:

    解决方案一:通过引入中间件来解决。 注意:不要验证观众

    1. 首先挂钩以下;

    ```

     JwtBearerOptions = options =>{
     options.Events = new JwtBearerEvents
    {
     OnTokenValidated = context =>
     {
        ...
        // this will put in the right aud
        // replace the entire principal
        var appIdentity = new ClaimsIdentity(newClaims);
        var claimsPrincipal = new ClaimsPrincipal(appIdentity);
        context.Principal = claimsPrincipal;
        }
      }
    }
    
    1. 介绍这个中间件;
      我在这里寻找 aud,但你的身份一切都是公平的。

    ```

    app.UseAuthentication();
    app.Use(async (HttpContext context, Func<Task> next) =>
    {
                //do work before the invoking the rest of the pipeline       
                if (context.Request.Headers.ContainsKey("x-authScheme") &&
                    context.Request.Headers.ContainsKey("Authorization") &&
                    context.User != null)
                {
                    // looking for bearer token stuff.
                    var claims = context.User.Claims;
                    var q = from claim in claims
                        where claim.Type == "aud" && claim.Value == "aggregator_service"
                        select claim;
                    if (!q.Any())
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        return;
                    }
                }
    
                await next.Invoke(); //let the rest of the pipeline run
    
                //do work after the rest of the pipeline has run     
    });
    

    ```

    【讨论】:

      猜你喜欢
      • 2017-10-26
      • 2019-09-26
      • 2020-01-20
      • 2021-04-29
      • 2016-08-06
      • 1970-01-01
      • 2020-04-04
      • 2019-09-14
      • 2019-11-01
      相关资源
      最近更新 更多