Jay Soares
Jay Soares

Reputation: 21

Using OnAuthorizationCodeReceived to retrieve Azure GraphAPI AccessToken

I am currently using code in my pipeline to cache the bearer token for the Graph API using Azure AD. This code was ported from a working ASP.NET 4 application, but it feels like the new OpenIdConnectOptions in Core should make this easier. Is there a more direct call that I can use in the OnAuthorizationCodeReceived event that will use the AuthenticationContext to cache the token once the code is received? Here is my current code:

var azureSettings = app.ApplicationServices.GetService<IOptions<AzureSettings>>().Value;
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ClientId = azureSettings.ClientId,
    ClientSecret = azureSettings.AppKey,
    Authority = string.Format(azureSettings.AadInstance, azureSettings.TenantId),
    Resource = azureSettings.GraphResourceUri,
    ResponseType = OpenIdConnectResponseType.CodeIdToken,
    TokenValidationParameters = new TokenValidationParameters
    {
        RoleClaimType = "roles"
    },
    Events = new OpenIdConnectEvents()
    {
        OnAuthorizationCodeReceived = (context) =>
        {
            string resourceUri = azureSettings.GraphResourceUri;
            var authContext = new AuthenticationContext(context.Options.Authority);
            var credential = new ClientCredential(context.TokenEndpointRequest.ClientId, context.TokenEndpointRequest.ClientSecret);
            var result = authContext.AcquireTokenByAuthorizationCodeAsync(context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri), credential, resourceUri);

            context.HandleCodeRedemption(result.AccessToken, result.IdToken);
        }
    }
});

The above code works just fine, but it feels like I am duplicating a lot of code just to submit what is mostly contained inside of the AuthorizationCodeReceivedContext already.

Is there an easier way that I am simply overlooking?

Upvotes: 1

Views: 5486

Answers (1)

Jay Soares
Jay Soares

Reputation: 21

After looking through the code for Microsoft.AspNetCore.Authentication.OpenIdConnect, I realized that this library is disconnected from the Token Caching mechanism within the AuthenticationContext. If I try and streamline the code, it will not trigger the caching mechanism which means the Bearer token needs to be retrieved on each request.

Because I plan to use the TokenCache to reduce the calls to the API and eventually leverage my Redis cache, I need to leave that code in the OnAuthorizationCodeReceived method.

Upvotes: 1

Related Questions