Home > Net >  How do I set Authorization Header for my HttpClient across all pages?
How do I set Authorization Header for my HttpClient across all pages?

Time:05-18

After contacting API in a login page with a successful login, I receive a JWT. And I want to set the AuthorizationHeader ONCE to use across all pages when navigating around.

I'm not sure if it's possible to do this with Dependency Injection on the HttpClient (with ClientFactory)? I.e. constructor inject HttpClient and set authorization header after successful login, does that save the state of the authorization header for use on all pages? (I tried this but doesn't work for me, but maybe I'm doing it wrong.)

Or do I need to pass the JWT-string around all the pages and set Authorization Header each time I change to a new page? To make any API calls, this seems weird to set everytime I call the authorized API? Which is the best approach?

This is for my .NET MAUI project (basically Xamarin, but newer).

CodePudding user response:

The best approach depends a lot on your implementation details. What happens if the API key isn't available or becomes invalid? Are you managing a single API key for any calls to the client, or are you managing multiple API keys for different scopes or multiple users?

One approach would be to build a Typed Client using HttpClientFactory; a typed client allows you to essentially write a custom class for which an HttpClient instance is injected and managed by the factory, and for which you can write specific behaviors that your client needs, such as handling API key checking and storage through dependency injection. You might write an interface/implementation called IAuthenticatedClient / AuthenticatedClient that exposes methods such as UpdateKey() and SendAuthenticatedAsync() where these methods sit on top of a persistent store such as an in-memory cache or database that retains the API key and applies it to calls before they're sent through the HttpClient, then register it with services.AddHttpClient<IAuthenticatedClient, AuthenticatedClient>(); and inject it where you need it.

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0#typed-clients

You might also consider implementing cross-cutting concerns such as API key application through the use of a delegating handler attached to a named or typed client, which is one of the cases described by Microsoft's documentation. Multiple handlers can be attached to create a middleware pipeline for outbound requests and responses sent through HttpClients to handle things like headers, logging, error handling, key management, etc.

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0#outgoing-request-middleware

  • Related