dmbuk
dmbuk

Reputation: 31

How to get Azure AD access token in Static Web App?

I have a vanilla Vue.JS SWA that uses a standard Azure AD authentication via these settings in staticwebapp.config.json:

"auth": {
    "identityProviders": {
      "azureActiveDirectory": {
        "registration": {
          "openIdIssuer": "https://login.microsoftonline.com/common/v2.0",
          "clientIdSettingName": "AZURE_CLIENT_ID",
          "clientSecretSettingName": "AZURE_CLIENT_SECRET"
        }
      }
    }
  }

An app with AZURE_CLIENT_ID is registered in Azure AD. Authentication is called via standard

/.auth/login/aad 

endpoint. I can successfully log in and log out. "/.auth/me" endpoint returns clientPrincipal object with all user details (roles, id, etc) and claims.

Now I want to call MS graph API https://graph.microsoft.com/v1.0/me, but don't know how to get the access token to set the Authorization header in the request. I can see that there is a AppServiceAuthSession cookie is set, however it is not a token.
I have seen this https://stackoverflow.com/questions/59860238/how-to-convert-azure-cookie-appserviceauthsession-to-a-valid-oauth-jwt-access-to , however reconstructing the whole auth flow looks unnecessary as I am logged in already.

Will appreciate any advice. Many thanks!

Tried to all MS Graph API as is, but as expected, got "message": "Access token is empty." Also had a look at azure/msal-browser module in a hope to get the token silently, but it looks super complex and badly documented for a JS novice like me.

Upvotes: 3

Views: 3705

Answers (3)

SEMICS
SEMICS

Reputation: 441

It does look like this feature is not available for Azure Static Web Apps unfortunately.

I have found a workaround which might be able to help someone (if you're using Javascript MSAL)

You can use the loginHint retrieved from the /.auth/me endpoint to quietly retrieve an auth token that you can send to your backend API.

See SSO between different apps for more info

import { PublicClientApplication } from '@azure/msal-browser'

const response = await fetch('/.auth/me')

const data = await response.json()

const msal = new PublicClientApplication(config.aad)
await msal.initialize()

const loginResponse = await msal.ssoSilent({
  loginHint: data.clientPrincipal.userDetails,
})

const accessToken = loginResponse.accessToken

console.log(accessToken)

Upvotes: 0

y. bs
y. bs

Reputation: 542

Its look like its currently not supported see this github issue: Add access token to user details endpoint.

Upvotes: 1

Mehtab Siddique
Mehtab Siddique

Reputation: 655

The following microsoft document shows getting the access on behalf of the user, you can refer this DOC to get the access token. Get a token

Hope this helps.

Upvotes: 0

Related Questions