I'm trying to write some authentication middleware for my web api (Using asp.net core) and I'm not sure how to indicate an authentication failure.
The idea is that I'd like to allow multiple methods of authentication, such as; basic (using the authorization header), having the credentials passed in the body of the request, maybe taking a bearer token etc.
The bit I'm not sure about is how to indicate success or failure from within the middleware. The only middleware I've written it to "do a thing" (Such as logging) and let the request carry on it's merry way.
If the authentication fails, how do I indicate that? I'd like to return an HTTP status code, but I'm not sure what happens to the rest of the request pipeline, does it abort in-place and go back through the prior middleware before that point?
Since this is authentication, I imagine it needs to be one of the first middleware in the pipeline.
If I intend to support multiple methods of authentication, would it be better to stick it all in the same middleware, or would it be possible (or better) to make it 1 authentication mechanism per middleware. If that's possible, how can I write in such a way as to distinguish between a "the supplied credentials are bad, fail here" and a "this middleware didn't find any appropriate credentials that it supports, but maybe the next one will".
I like the idea of 1 piece of middleware does 1 thing, but I'm not keen on the middleware needing to know that it's the last in the chain, as it relies on the developer putting it in the correct order (easy to forget and move it around later).
Thanks.
There's a whole authentication / authorization framework for Asp.Net Core that's worth reading up on.
The first thing to consider is separating authentication from authorization. Authentication middleware look at the request and try to produce a ClaimsIdentity. If they fail they do not need to terminate the request, they can let it continue anonymously. This allows you to chain multiple kinds of auth.
After you get through the authentication middleware, then you can do authorization on the results. You can do this as one blanket middleware, or more granularly per MVC Controller or Action.
In general though, middleware order is frequently important to a well functioning app.