jeudi 9 septembre 2021

A better way to set access token on service layer

We are creating a Blazor Server Side Project (Web), and we do have another project (Services) which contains all the services and those are injected on Web project initialization.

The thing is: those services consume an API which for every call requires a bearer token. So currently, every Service method contains an AccessToken parameter, just like:

public async Task<PagedList<Entity>> GetEntitiesAsync(string accessToken)
{
    var client = new RestClient ...
    var request = new RestRequest(Method.GET);
    request.AddHeader("authorization", $"Bearer {accessToken}");
    ...
}

And this keeps on, and on, for every service method. I'm trying to think what to do in order to "inject" that access token. But don't seem to find how...

At Web initialization I don't know the JWT, because no user is logged in. So I must wait, but after that? How? Keep passing the accessToken as a parameter smells like pretty bad code to me.

Thanks.

Aucun commentaire:

Enregistrer un commentaire