Add MSAL to ApolloServer

Install libraries to validate tokens by opening a console in data-access project and issuing the following commands

/azure-quickstart/data-access/
npm install jose
npm install openid-client

In /azure-quickstart/data-access/ create the directories sharedCode/auth .

In the auth directory, create a new file msal.ts and add the following code.

/azure-quickstart/data-access/shared-code/auth/msal.ts
import { Issuer, Client } from 'openid-client';
import {JWT} from 'jose';

var verifyAccessToken = async (context) : Promise<[object, boolean]>  => {
  let token = context.request.headers["authorization"];
  if (!token || !token.startsWith("Bearer ")) return [{}, false];

  token = token.slice(7, token.length).trimLeft(); // Remove 'Bearer ' characters from start of Auth header value

  const settings = {
    audience: process.env.AAD_TOKEN_APPLICATION_ID,
    openIdConfigUrl: process.env.AAD_TOKEN_OPEN_ID_CONNECT_METADATA_DOCUMENT,
    tenantId: process.env.AAD_TOKEN_TENANT_ID
  };

  const issuer = await Issuer.discover(settings.openIdConfigUrl);
  const keyStore = await issuer.keystore();

  var results = JWT.verify(
    token,
    keyStore, 
    {
      audience: settings.audience,
     // issuer: 
        //issuer must remain commented out if you're accepting tokens from :
        // Microsoft's public endpoint (which will be: 'https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0' or it can be any AAD tenant's ID)
        //if you only want to accept local AAD Accounts use: `https://login.microsoftonline.com/${settings.tenantId}/v2.0`
    }
  );
  
  return [
    {
      "authToken": results,
    },
    true
  ];
}

export default {
  VerifyAccessToken: verifyAccessToken
}

Replace the contents of the main function file with the following to properly reference MSAL and to allow for auth headers.

Update the local settings to supply the function with the appropriate values:

Azure Settings

Open the data-access function App

  • In the function app navigate to Configuration

    • Choose + New Application Setting for each of the following

      • Name: AAD_TOKEN_OPEN_ID_CONNECT_METADATA_DOCUMENT

        • Value: <<SAME VALUE AS USED IN LOCAL SETTINGS>>

      • Name: AAD_TOKEN_APPLICATION_ID

        • Value: <<SAME VALUE AS USED IN LOCAL SETTINGS>>

      • Name: AAD_TOKEN_TENANT_ID

        • Value: <<SAME VALUE AS USED IN LOCAL SETTINGS>>

      • Name: APOLLO_PLAYGROUND_URI

        • Value: <<AZURE FRONT DOOR URL>>/api/graphql (e.g.: https://sharethrift<<random number>>.azurefd.net/api/graphql)

  • Choose Save

  • Choose Continue (wait until completion)

Repeat the same steps for the data-access-west function app.

Important Warnings

Last updated

Was this helpful?