Yves Schelpe
Yves Schelpe

Reputation: 3463

Getting GraphService accesstoken in ASP.NET Core 2.0 AzureAD

I'm currently trying to automatically setup a graphservice whenever my application starts. I have following code:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(sharedOptions =>
        {
            sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddAzureAd(options =>
            {
                Configuration.Bind("AzureAd", options);
            })
        .AddCookie();

        services.AddMvc();
    }

Inside or after the AddAzureAd I'd like to register and configure a GraphService to connect to MS AAD Graph Api https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-graph-api

Yet I have no idea how to get an accesstoken which every example speaks of. I ticked the box on the template "Read" from Graph API, so I though this would be configured automatically, sadly it isn't.

Upvotes: 0

Views: 453

Answers (1)

Fei Xue
Fei Xue

Reputation: 14649

To acquire the access token in the asp.net core with OpenIdConnect protocol, we need to use OnAuthorizationCodeReceived event like code below:

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ClientId = ClientId,
    Authority = Authority,
    PostLogoutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"],
    ResponseType = OpenIdConnectResponseType.CodeIdToken,
    GetClaimsFromUserInfoEndpoint = false,

    Events = new OpenIdConnectEvents
    {
        OnRemoteFailure = OnAuthenticationFailed,
        OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
    }
});  

private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{


       // Acquire a Token for the Graph API and cache it using ADAL.  In the TodoListController, we'll use the cache to acquire a token to the Todo List API
        string userObjectId = (context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
        ClientCredential clientCred = new ClientCredential(ClientId, ClientSecret);
        AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId, context.HttpContext.Session));
        AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
            context.ProtocolMessage.Code, new Uri(context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]), clientCred, GraphResourceId);

        // Notify the OIDC middleware that we already took care of code redemption.
        context.HandleCodeRedemption();
}

More detail about acquire access_token in the asp.net core, you can refer the code sample below:

active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore

Upvotes: 1

Related Questions