Skip to content

Instantly share code, notes, and snippets.

@kasthor
Created April 20, 2021 01:34
Show Gist options
  • Save kasthor/181239426233ab51a5ee3d12b6802add to your computer and use it in GitHub Desktop.
Save kasthor/181239426233ab51a5ee3d12b6802add to your computer and use it in GitHub Desktop.
Authenticate to Azure with Hooks
import { PublicClientApplication } from "@azure/msal-browser";
import { Client } from "@microsoft/microsoft-graph-client";
import React, { useState, createContext, useEffect } from "react";
export const AzureAuthContext = createContext({});
export const AzureAuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [userProfile, setUserProfile] = useState({});
const ACTIVE_DIRECTORY_SCOPES = ['user.read'];
const azureClientApp = new PublicClientApplication({
auth: {
clientId: process.env.NEXT_PUBLIC_AZURE_ACTIVE_DIRECTORY_APP_CLIENT_ID,
redirectUri: process.env.NEXT_PUBLIC_AZURE_ACTIVE_DIRECTORY_REDIRECT_URI,
authority:
`https://login.microsoftonline.com/${process.env.NEXT_PUBLIC_AZURE_ACTIVE_DIRECTORY_TENANT_ID}`,
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
},
});
const getUserDetails = (token) => {
const client = Client.init({
authProvider: (callback) => callback(null, token),
});
return client.api("/me").select("*").get();
};
const getAccessToken = async (scopes) => {
const accounts = azureClientApp.getAllAccounts()
if (accounts.length <= 0) throw new Error("login_required");
const result = await azureClientApp.acquireTokenSilent({
scopes,
account: accounts[0],
});
return result.accessToken;
};
const getUserProfile = async () => {
try {
const token = await getAccessToken(ACTIVE_DIRECTORY_SCOPES);
if (token) {
setIsAuthenticated(true);
setUserProfile(await getUserDetails(token));
}
} catch (e) {
setIsAuthenticated(false);
setUserProfile({});
}
};
const login = async () => {
await azureClientApp.loginPopup({
prompt: "select_account",
scopes: ACTIVE_DIRECTORY_SCOPES,
});
await getUserProfile();
};
const logout = () => {
console.log("LOGOUT");
return azureClientApp.logout();
}
useEffect(async () => {
await getUserProfile();
}, []);
return (
<AzureAuthContext.Provider value={{ login, logout, isAuthenticated, userProfile }}>
{children}
</AzureAuthContext.Provider>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment