2

I'm currently using Ocelot as Api Gateway for a micro-services architecture. I have some authenticated reroutes and to be able to use it I declared a authentication Middleware like this :

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
            };
        });

I wanted to run some custom validation to implement refresh token workflow, to do so I implemented the preAuthentication Middleware to make so tests :

 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();
                    }
                }
            }

From what I understood, when I make an api Call, the preAuthenticate Middleware would be called, and with next.Invoke() my Authentication middleware would be called. The newly generated token in my PreAuthentication middleware is a valid one, but my authentication middleware throws an expiredToken exception even tho he's not. Therefore I think the authentication Middleware is run against the first JWT when the new one has not been yet set to the Authorization Header. Is it the attended behaviour? Or maybe I did not understood correctly the middleware in Ocelot?

Anyway, some help would be much appreciated !

Have a good day,

Lio

lioleveau
  • 518
  • 1
  • 6
  • 23

0 Answers0