0
votes

We are trying to access the calendar events of the current user from a asp.net core 2.2 web api project. We are using Azure AD authentication and that JWT token is passed by the Angular application. I'm using the following code to get the Graph token.

var token = Request.Headers["Authorization"].ToString();

var app = ConfidentialClientApplicationBuilder.Create(config.ClientId) // Has GUID of registered app
    .WithAuthority(config.Authority)  // URL + Tenant ID
    .Build();

// THIS LINE THROWS THE EXCEPTION
var graphToken = await app.AcquireTokenOnBehalfOf(new List<string> { "Calendars.ReadWrite" },
    new Microsoft.Identity.Client.UserAssertion(token)).ExecuteAsync();

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", graphToken.AccessToken);
var response = await client.GetAsync("https://graph.microsoft.com/v1.0/me");
var content = await response.Content.ReadAsStringAsync();

return Ok(content);

Not really sure why I'm getting this error. token has the JWT generated by Azure AD. I have tried with and without the Bearer prefix of the token with the same result.

Thank you,

1
How do you call that code? I wonder if the exception is marked in the incorrect placeCamilo Terevinto
This code is inside a controller on the Web API projectFernando
You seem to be mixing stuff. Maybe include a link to the documentation you're trying to use. If you use the token in angular, why not have angular request the token? docs.microsoft.com/en-us/azure/active-directory/develop/…Stephan
@Stephan because I'm trying to get calendar events on the API. The user is authenticated with Azure AD but I need to access their calendar through MS Graph which requires the API to get a different token with the identity of the user in the authentication token.Fernando
Which flow is used?Stephan

1 Answers

0
votes

I had to change strategies and change our flow to use V2.0 tokens from Azure AD.

Also I used this code (https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2) to facilitate getting the MS Graph Authentication Token.

Thank you.