I am trying to implement the Azure AD Graph API in an MVC Web App hosted on Azure. The Azure AD is set up correctly as I was able to use the Graph API last year in a previous version before it got updated at some point late last year/this year.
I am following the instructions here https://github.com/AzureADSamples/WebApp-GraphAPI-DotNet and using the updated code. The difference between these two projects is I am using WsFed not OpenID, so some parts are different, namely Startup.Auth.cs. Here is the relevant code in this example project (seen here):
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(clientId, appKey);
string userObjectID = context.AuthenticationTicket.Identity.FindFirst(
"http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
AuthenticationHelper.token = result.AccessToken;
return Task.FromResult(0);
}
}
However, since my website it set up that you have to be logged in through WS-Fed to access anything on the site at all, I try to get a token in Startup.Auth.cs. so that I can simply use AcquireTokenSilent later. I use the project here https://github.com/AzureADSamples/WebApp-WSFederation-DotNet to setup WS-Fed.
The problem in Startup.Auth.cs is that I don't have access to the AuthorizationCodeReceived option, only SecurityTokenReceived and SecurityTokenValidated. Neither of these give a good option for an access code or anything that I can use to query the Graph API later in my application. How do I do this? Any guidance would be greatly appreciated.
unfortunately the WS-Federation protocol does not have any concept of client and access token - the only token being traded is the one sent to you for the web login, and there is no authorization code generated. If you need to call the Graph API, I strongly recommend switching to OpenId Connect (which does handle the access token acquisition using the logic you reported above). If you absolutely cannot switch out from ws-fed, you need to perform OAuth2 flows manually. In practice, this means taking the code from https://github.com/AzureADSamples/WebApp-WebAPI-OAuth2-AppIdentity-DotNet or https://github.com/AzureADSamples/WebApp-WebAPI-OAuth2-UserIdentity-DotNet and plaster it on top of your app. That's not a very clean cut task, which is why I stand by my recommendation to take advantage of the integrated flow offered by OpenId Connect. HTH V.