Kevin Welsh
Kevin Welsh

Reputation: 139

ADAL Token used on server for Graph API

I'm developing an Angular2+ app that authenticates with Azure AD. I need to pass the token to my Web API layer (this works successfully using an HttpInterceptor), then use that token on the server side to call into Microsoft Graph.

How can I convert the one token into the other, ideally on the server?

Upvotes: 2

Views: 715

Answers (1)

juunas
juunas

Reputation: 58898

Exactly the scenario for On-Behalf-Of flow.

Here's the blog article I wrote on it: https://joonasw.net/view/azure-ad-on-behalf-of-aspnet-core.

That is a fairly long sentence, so let's look at an example scenario where this is used:

  • A JavaScript Single Page Application authenticates the user with Azure AD
  • The SPA gets an access token for its back-end API and calls the API
  • The API then needs to get information about the user's manager from Microsoft Graph API

In this scenario, there are basically two options:

  1. Use the on-behalf-of grant to acquire an access token that allows the API to call MS Graph as the user
  2. Use client credentials grant to make the call as the API, with no user context

The first option uses delegated permissions, which mean the data that can be returned is based on what the API and user are allowed to access. It does require the call made to this API was made with a user context.

The second option would instead use application permissions, in which case the app itself would need to have access to this information for any user in the organisation.

You can probably understand why using delegated permissions is usually preferred. It follows the principle of least privilege.

You can find the sample app used in this article at https://github.com/juunas11/azure-ad-on-behalf-of-sample-aspnetcore.

So you can basically exchange the token you got from the SPA, along with the API's credentials to get a new access token for another API. This new token will also be in user context, and will use delegated permissions.

Here is an example HTTP request which does the token exchange:

POST https://login.microsoftonline.com/joonasapps.onmicrosoft.com/oauth2/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: login.microsoftonline.com
Content-Length: 1650
Expect: 100-continue
Connection: Keep-Alive

grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&client_id=f3c39179-62f7-45fc-a469-a64fdfce4f91&client_secret=REDACTED&resource=https%3A%2F%2Fgraph.microsoft.com&assertion=eyJ0eLongAccessTokenForThisApi&requested_token_use=on_behalf_of

You can find more info here: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-on-behalf-of

Upvotes: 2

Related Questions