How do you get the access_token claim in a controller action?

Viewed 331

I've integrated OpenIddict in an asp.net core web api. It seems to be working as far as I can tell. Now, I am joining the OpenIddict tables to my applications tables. I have added UserKey to the OpenIddictApplications table. I have the OpenIddict token and application managers injected into my controller. Now, in each controller method, I want to get the access_token so I can use that to get the application and then run queries across my data model, so I can build the model object and return that to the caller as json.

Below is what I tried. The request is null and so the subsequent lines fail to do anything useful, of course.

 [Authorize(AuthenticationSchemes = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme)]
 [HttpGet(Name = "GetFacilities")]
 public async Task<ActionResult<FacilityDirectory>> GetFacilities()
 {
        var request = HttpContext.GetOpenIddictServerRequest();
        var accessToken = request.AccessToken;
        var appId = await _tokenManager.GetApplicationIdAsync(accessToken);
        var application = await _applicationManager.FindByIdAsync(appId);
        var userKey = ((CustomApplication)application).User.UserKey;

        // rest ommitted for brevity
 }

What do I need to be using to get that access token value?

1 Answers

I used Active Directory B2C services for user login and then getting an access token to access APIs. This is how I retrieved the access token inside controller. Not sure but I guess this should work irrespective of which service is generating the access token (in your case openiddict). Try this out if you like.

public MyController(IHttpContextAccessor contextAccessor, ...)
{
    var MyContext = contextAccessor.HttpContext;
    var AuthType = MyContext.User.Identity.AuthenticationType;
    var MyAccessToken = await MyContext.GetTokenAsync(AuthType, "access_token");    
}    

    
Related