servicestack

How do you authenticate JsonApiClient with a JWT BearerToken?


I'm using IClientAccessTokenManagementService from Identity Model to obtain a JWT token that will authorize my client.

I'm setting Bearer Token, but keep getting 403 Unauthorized. I wish I could use CaptureHttp but that isn't available with the JsonApiClient

ServiceStack docs say to use JsonApiClient, but then shows all the docs using JsonServiceClient.

// JsonServiceClient works
var jsc = new JsonServiceClient(myCompanyApi);
jsc.CaptureHttp(log: true); // function not available with JsonApiClient
jsc.BearerToken = myClientAccessToken;
var jscResults = jsc.Get(request);

// JsonApiClient returns Failed and Unauthorized
// _jsonApiClient instance is from named HttpClient in the Factory 
_jsonApiClient.BearerToken = myClientAccessToken;
var apiResults = _jsonApiClient.Api(request);

clarifying update

If I set the bearer token directly on the underly http client then the JsonApiClient is successful

_jsonApiClient.HttpClient.SetBearerToken(myClientAccessToken);


Solution

  • Your BearerToken needs to be set when initializing the JsonApiClient, e.g:

    var client = new JsonApiClient(myCompanyApi) {
        BearerToken = myClientAccessToken,
    };
    

    Which will be populated on the underlying HttpClient instance that gets constructed when sending the first request.

    To populate it after requests have been made you'll need to set it on the underlying HttpClient, e.g:

    client.GetHttpClient().DefaultRequestHeaders.Authorization = 
        new AuthenticationHeaderValue("Bearer", myClientAccessToken)