A this moment, i've an Ocelot API Gateway in my microservice, but i recently i was looking how to invalidate a JWT, and the best way to do this in my project is using a blacklist, so i decided to use a middleware pre authorization to check in my Redis cache the list of invalid JWT. I've looked for solutions to force return a 401 with custom message if the token is in the cache, but i can't find a functional solution. Below is my try:
public async void Configure(IApplicationBuilder app, IWebHostEnvironment env, IDistributedCache cache) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapGet("/", async context => {
await context.Response.WriteAsync("Hello World!");
});
});
var configuration = new OcelotPipelineConfiguration {
PreAuthorizationMiddleware = async (ctx, next) => {
string token = ctx.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
if (!string.IsNullOrEmpty(token)) {
string blacklist = await cache.GetStringAsync(token);
if (!string.IsNullOrEmpty(blacklist)) {
ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await ctx.Response.WriteAsync("Custom Message");
return;
}
}
await next.Invoke();
}
};
await app.UseOcelot(configuration);
}
Can someone help me? The solutions i've tried only returns HTTP status code 500 or always 401.
Once you are in Ocelot's pipeline, you have to play Ocelot's game. It uses special objects and extension methods on HttpContext.Items
dictionary to pass data between middlewares. Specifically for errors it has 2 extension methods SetError
and UpsertErrors
. So you need to add this after checking the black list:
if (!string.IsNullOrEmpty(blacklist))
{
ctx.Items.SetError(new UnauthorizedError("your custom message"));
return;
}