Skip to content
This repository has been archived by the owner on Jun 30, 2023. It is now read-only.

Acquiring tokens with authorization codes on web apps

Jean-Marc Prieur edited this page Aug 28, 2018 · 3 revisions

When users login to Web applications (web sites) using Open Id connect, the web application receives an authorization code which it can redeem to acquire a token for Web APIs.

Getting tokens by authorization code in ADAL.NET

image

This is illustrated in several samples, for instance active-directory-dotnet-webapp-webapi-openidconnect sample.

  private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification 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));
   Uri uri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

   AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code,
                                                            uri, credential, graphResourceId);
  }

See details in Startup.Auth.cs#L94-L104

Note that the code is usable only once to redeem a token. AcquireTokenByAuthorizationCodeAsyncshould should not be called several times with the same authorization code (it's explicitly prohibited by the protocol standard spec)

It's a first step to make calls to other Web APIs on behalf of the user

AcquireTokenByAuthorizationCodeAsync is usually the first step, as this token gets in the token cache (note the following code)

new NaiveSessionCache(userObjectId) 

Then once it's in the cache, the token will be used to call other web APIs in the name of the users by leveraging the on-behalf-of flow. See for instance TodoListController.cs#L56

For more details, see also Service to service calls on behalf of the user

Samples illustrating AcquireTokenByAuthorizationCodeAsync

Sample Platform Description
active-directory-dotnet-webapp-webapi-openidconnect ASP.NET Web App, Web API A .NET 4.5 MVC web app that signs Azure AD users in with OpenID Connect and calls a web api using OAuth 2.0 access tokens
active-directory-dotnet-webapp-openidconnect-aspnetcore ASP.NET Core 2.0 Web App An ASP.NET Core web application that signs-in Azure AD users from a single Azure AD tenant
active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore ASP.NET Core 2.0 Web App, ASP.NET Core 2.0 Web API An ASP.NET Core web application that authenticates Azure AD users and calls a web API using OAuth 2.0 access tokens
Clone this wiki locally