How can I stop a request in Ocelot's PreAuthenticationMiddleware?

Viewed 1943

I have to do some checks on the request's jwt before ocelot authentication, so I'm doing them within the PreAuthenticationMiddleware like this:

var config = new OcelotPipelineConfiguration
{
    PreAuthenticationMiddleware = async (ctx, next) =>
    {
        var jwt = ctx.HttpContext.Request.Headers["Authorization"];

        if (jwtIsOk(jwt)) next.Invoke();
        // else ...
    }
};

app.UseOcelot(config).Wait();

Instead of not-invoking next, is it possible to return a custom response?

I'd like to return a 401 error

1 Answers

I think this is what you are looking for :

        var configuration = new OcelotPipelineConfiguration
        {
            PreAuthenticationMiddleware = async (ctx, next) =>
            {
                if (xxxxxx) 
                {
                    ctx.Errors.Add(new UnauthenticatedError("Your message"));

                    return;
                }

                await next.Invoke();
            }
        };

In this case I'm using UnauthenticatedError(an Ocelot's class), it will ends with 401. There are more like this. You can also create your own one inheriting from Ocelot.Errors.Error.

Related