Search code examples
asp.net-coreasp.net-identityjwtidentityserver4

identityserver 4 get current user's access_token


I am having trouble getting my current user's access_token. Here is my setup:

  • QuickstartIdentityServer (QIS) in aspnet core, identity and EF storage
  • API (API) in NodeJs. Validates jwt tokens in header against QIS.
  • SPA angular app that works great with QIS and API and is out of the scope of this question

In a section of the QuickstartIdentityServer (QIS) site (user details page), I would like to call an API endpoint using an access_token to authenticate the request. I am struggling to retrieve the current user's access_token from my QIS site. Whenever I call HttpContext.GetTokenAsync("access_token") I get a null value. I have seen this section of IdSrv4 documentation: https://identityserver4.readthedocs.io/en/release/quickstarts/5_hybrid_and_api_access.html?highlight=gettokenasync but it seems to apply to an MVC client and not my own identity server.

Anyone could shed some light on how to get my user's access_token ?

Thanks

EDIT

Here is a starting point to try to explain better my issue: https://github.com/IdentityServer/IdentityServer4.Samples/tree/release/Quickstarts/6_AspNetIdentity/src/IdentityServerWithAspNetIdentity

Starting from this QIS project, I would like to get the logged in user's access token. So for instance, if I edit HomeController to add this call:

public async Task<IActionResult> Index()
{
     var accessToken = await HttpContext.GetTokenAsync("access_token");
     return View(accessToken);
}

I would then be able to call my NodeJS API with this token in the Auth Header.

Hope this explains better my issue.


Solution

  • So I managed to authenticate myself w/ my API using a dedicated Client using client credentials grant and the following call to get an access_token:

            var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
            var tokenClient = new TokenClient(disco.TokenEndpoint, clientId, clientSecret);
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync(scope);
    

    Then I can add to my request header to API the access_token returned in tokenResponse:

            using(var client = new HttpClient()) {
              client.SetBearerToken(tokenResponse.AccessToken);
              ...
              // execute request
            }
    

    The downside is that I can't "impersonate" the current currently logged on IS on API side.