I would like to get your opinion on the problem I am having, my question on SO was closed so I think this forum might be more fitting.
I am currently developing a API using .NET 5 and C#. The problem I am facing is that the clients I need to GET/POST etc. to require different types of authentication, being:
- API Key
- Client certificate
Each of the clients have at least one of these and maybe two (API Key + other). I am struggling to figure out how to implement these calls. I have thought of a few ideas but I am not sure if any of them will actually suffice. I am using
HttpClient to make the calls to the external clients. These will all come from a single service or controller. I cannot split them out into a different service or controller for each type of auth.
Here is what I have thought of:
- Using an if or switch statement, apply the necessary configuration depending on the required auth type. This is by far the worst idea, there will be so much repetition. No DRY here.
HttpClienthandlers. In effect, creating three handlers (one for each type of auth) and letting the request activate the correct handler when it is being passed through.
- Using a typed client. But this only allows one
HttpClientto be related to a single service. I need all three to be available to any service.
- Using simple middleware in the API to handle the requests and their authentication as necessary.
Does anyone have any suggestions on how to do this and if any of the above methods would be preferable?