Andrés Nava - .NET Andrés Nava - .NET - 1 year ago 113
AngularJS Question

Pass received JWT token from one service to another

I have this fairly straightforward use-case:

  • Resource owner uses my Angular client to obtain a JWT token from IDP

  • Angular client calls Service A (WebAPI) with the JWT token issued by IDP

  • Angular client calls Service B (WebAPI) with the JWT token issued by IDP

I would like to support the following scenario:

  • Have Service A act like the Angular client and pass-through the JWT token it received to make a call to Service B

So basically, Service B can be called either directly by the Angular client or by Service A. In both cases, it must be provided a Bearer token in order to access any of the WebAPI endpoints.

From Service A, I do not know how to store the provided token so that later on when I need to use the
to call Service B I can set the

Answer Source

If I understood correctly, your requirement is to call the second API (Service B) as part of a single request to Service A from an authenticated user.

If this is the situation, then I believe there is no reason to store the token server-side, and you may just take the Authorization header from the current request and reuse it to call Service B.

Some code may help explain what I mean, assuming ControllerA is a Service A controller:

public class ControllerA : ApiController
    public async Task<IHttpActionResult> GetFromB()
        var token = Request.Headers.Authorization.Parameter;

        MyModel result = null;

        using (var client = new HttpClient())
            client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", token);

            var response = await client.GetAsync("http://serviceb/controllerb/actionb");
            result = await response.Content.ReadAsAsync<MyModel>();

        return Ok(result);