Skip to main content
Unlisted page
This page is unlisted. Search engines will not index it, and only users having a direct link can access it.

Azure AD B2C, MSAL, Axios - Code Snippets

ยท 2 min read
Shaw Innes

I've collated the following code snippets as an MVP for adding an Access Token to API requests using AXIOS. The full explanation is available here

yarn add @azure/msal-browser @azure/msal-react
services/msal.ts
import * as msal from "@azure/msal-browser";
import {Configuration, RedirectRequest} from "@azure/msal-browser";

const msalConfig = {
auth: {
clientId: 'your_client_id',
authority: "https://tenant.b2clogin.com/tenant.onmicrosoft.com/b2c_1_susi",
knownAuthorities: ["tenant.b2clogin.com"],
}
};

const scopes = [
'your_client_id'
]

const loginRequest: RedirectRequest = {
scopes: scopes
}

const msalInstance = new msal.PublicClientApplication(msalConfig);

export {msalInstance, loginRequest, scopes}
services/axios.ts
import axios, {AxiosRequestConfig} from "axios";
import {scopes, msalInstance} from "./msal";

const instance = axios.create({
baseURL: process.env.REACT_APP_API_URL
});

instance.interceptors.request.use(
async (config: AxiosRequestConfig) => {
if (config.headers) {
config.headers['Content-Type'] = 'application/json';
}

const account = msalInstance.getAllAccounts()[0];
if (account) {
const accessTokenResponse = await msalInstance.acquireTokenSilent({
scopes: scopes,
account: account
});

if (accessTokenResponse) {
const accessToken = accessTokenResponse.accessToken;

if (config.headers && accessToken) {
config.headers['Authorization'] = 'Bearer ' + accessToken;
}
}
}
return config;
},
error => {
Promise.reject(error)
});

export default instance;
index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import {MsalProvider} from '@azure/msal-react';
import {msalInstance} from "./services/msal";

ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<MsalProvider instance={msalInstance}>
...
</MsalProvider>
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);

sign-in-button.ts
import {useMsal} from "@azure/msal-react";
import {loginRequest} from "../services/msal";

const SignInButton = () => {
const {instance} = useMsal();
return <button onClick={() => instance.loginRedirect(loginRequest)}>Sign In</button>;
}

export default SignInButton;

get token (including Access Token)

import {scopes, msalInstance} from "../services/msal";

const account = instance.getAllAccounts()[0];
if (account) {
const accessTokenResponse = await msalInstance.acquireTokenSilent({
scopes: scopes,
account: account
});

console.log(accessTokenResponse); // do something smart here
}