Ocelot Asp.net核心预身份验证中间件

时间:2020-02-21 08:27:49

标签: c# asp.net-core api-gateway ocelot

我目前正在将Ocelot用作微服务架构的Api网关。我有一些经过身份验证的重新路由,并且能够使用它,我这样声明了身份验证中间件:

var authenticationProviderKey = "Authentification";
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(authenticationProviderKey, x =>
        {
            x.RequireHttpsMetadata = false;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
                ValidIssuer = token.Issuer,
                ValidAudience = token.Audience,
                ValidateIssuer = true,
                ValidateAudience = true
            };
        });

我想运行一些自定义验证来实现刷新令牌工作流,为此,我实现了preAuthentication Middleware来进行测试:

 PreAuthenticationMiddleware = async (ctx, next) =>
            {
                IEnumerable<string> header;
                ctx.DownstreamRequest.Headers.TryGetValues("Authorization", out header);
                if (header.FirstOrDefault() != null)
                {
                    if (JwtUtils.ValidateExpirationToken(header.FirstOrDefault()))
                    {
                        //On validate refresh token
                        Console.WriteLine("PreAuthentification Middleware");
                        Tuple<int, string> credentials = JwtUtils.retrieveInfos(header.FirstOrDefault());
                        string token = JwtUtils.GenerateToken(credentials.Item1, credentials.Item2);
                        ctx.DownstreamRequest.Headers.Remove("Authorization");
                        ctx.DownstreamRequest.Headers.Add("Authorization", token);
                        await next.Invoke();
                    }
                }
            }

据我了解,当我进行api调用时,将调用preAuthenticate中间件,并使用next.Invoke()调用我的身份验证中间件。我的PreAuthentication中间件中新生成的令牌是有效令牌,但是我的身份验证中间件抛出了expiredToken异常,即使不是。因此,我认为,当尚未将新的中间件设置为授权头时,将对第一个JWT运行验证中间件。是有人照看的行为吗?或者,也许我对Ocelot中的中间件没有正确的理解?

无论如何,我们将不胜感激!

祝你有美好的一天,

Lio

0 个答案:

没有答案