feat(web): add client utilities
This commit is contained in:
1 parent
a796620b7f
commit
39f3221640
7 files changed
+335
No files matched your search
@@ -0,0 +1,10 @@
|
||||
import { MsalProvider } from '@azure/msal-react';
|
||||
import { msalInstance } from './msal.config';
|
||||
|
||||
export function MsalAppProvider({ children }: { children: React.ReactNode }) {
|
||||
if (!msalInstance) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
return <MsalProvider instance={msalInstance}>{children}</MsalProvider>;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import {
|
||||
PublicClientApplication,
|
||||
type Configuration,
|
||||
} from '@azure/msal-browser';
|
||||
|
||||
const clientId = (import.meta.env.VITE_MSAL_CLIENT_ID ?? '').trim();
|
||||
const authority = (import.meta.env.VITE_MSAL_AUTHORITY ?? '').trim();
|
||||
const redirectUri = (import.meta.env.VITE_MSAL_REDIRECT_URI ?? '').trim();
|
||||
|
||||
export const MSAL_API_SCOPE = (
|
||||
import.meta.env.VITE_MSAL_API_SCOPE ?? ''
|
||||
).trim();
|
||||
|
||||
export const MSAL_SILENT_REDIRECT_URI = (
|
||||
import.meta.env.VITE_MSAL_SILENT_REDIRECT_URI ??
|
||||
`${window.location.origin}/auth/silent-callback.html`
|
||||
).trim();
|
||||
|
||||
export const isMsalConfigured = Boolean(
|
||||
clientId &&
|
||||
authority &&
|
||||
MSAL_API_SCOPE &&
|
||||
!authority.includes('<tenant-id>'),
|
||||
);
|
||||
|
||||
export const msalConfig: Configuration = {
|
||||
auth: {
|
||||
clientId,
|
||||
authority,
|
||||
redirectUri: redirectUri || window.location.origin,
|
||||
postLogoutRedirectUri: window.location.origin,
|
||||
},
|
||||
cache: {
|
||||
cacheLocation: 'localStorage',
|
||||
},
|
||||
};
|
||||
|
||||
export const msalInstance = isMsalConfigured
|
||||
? new PublicClientApplication(msalConfig)
|
||||
: null;
|
||||
@@ -0,0 +1,26 @@
|
||||
import {
|
||||
isMsalConfigured,
|
||||
MSAL_API_SCOPE,
|
||||
MSAL_SILENT_REDIRECT_URI,
|
||||
msalInstance,
|
||||
} from './msal.config';
|
||||
|
||||
export async function acquireAccessToken(): Promise<string | null> {
|
||||
if (!isMsalConfigured || !msalInstance) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const accounts = msalInstance.getAllAccounts();
|
||||
const account = msalInstance.getActiveAccount() ?? accounts[0];
|
||||
if (!account) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const response = await msalInstance.acquireTokenSilent({
|
||||
account,
|
||||
scopes: [MSAL_API_SCOPE],
|
||||
redirectUri: MSAL_SILENT_REDIRECT_URI,
|
||||
});
|
||||
|
||||
return response.accessToken;
|
||||
}
|
||||
Reference in new issue
Block a user