React-Apollo msal-browser with msal-react wrapper不能获取帐户



我正在将我的包从react-adal移动到@azure/microsoft -react。在react-adal中,我可以授权并能够去我的应用程序。我使用相同的client_idTenant_id,但似乎getAllAccounts()返回我空数组,这意味着没有用户发现,结果我没有得到任何令牌。我跟医生说的一模一样。我不知道我犯了什么错误。

这是我的设置

import { Configuration, PopupRequest, PublicClientApplication } from '@azure/msal-browser'
export const msalConfig: Configuration = {
auth: {
clientId: process.env.NEXT_PUBLIC_MSAL_CLIENT_ID || '',
redirectUri: process.env.NEXT_PUBLIC_MSAL_REDIRECT_URL,
authority: `https://login.microsoftonline.com/${process.env.NEXT_PUBLIC_MSAL_TENANT}`,
navigateToLoginRequestUrl: true,
},
cache: {
cacheLocation: 'localStorage', // This configures where your cache will be stored
storeAuthStateInCookie: false,
},
}
export const loginRequest: PopupRequest = {
scopes: ['User.Read'],
}
export const msalInstance = new PublicClientApplication(msalConfig)
const currentAccounts = msalInstance.getAllAccounts()
console.log({ currentAccounts }) // returns empty array

这是我如何扭曲我的应用程序与MsalProvider

import { ApolloProvider } from '@apollo/client'
import { MsalProvider } from '@azure/msal-react'
import { defaultClient } from 'apollo'
import { msalInstance } from 'msal-auth-config' // import msalInstance from config
import type { AppProps } from 'next/app'
import React from 'react'

const App = ({ Component, pageProps }: AppProps): JSX.Element => {
return (
<MsalProvider instance={msalInstance}>
<ApolloProvider client={defaultClient}>
<App />
</ApolloProvider>
</MsalProvider>
)
}
export default App

这里我想返回token

const authLink = setContext((_operation, { headers }) => {

const accounts = msalInstance.getAllAccounts()
//console.log({ accounts, headers })
if (accounts.length > 0) {
msalInstance.setActiveAccount(accounts[0])
}
return msalInstance
.acquireTokenSilent(loginRequest)
.then((response) => {
console.log(response) // return undefined
return { headers: { ...headers, Authorization: `Bearer ${response.idToken}` } }
})
.catch((error) => {
if (error instanceof InteractionRequiredAuthError) {
return msalInstance.acquireTokenRedirect(loginRequest)
}
return
})
})

你试过这样做吗

import { useState, useEffect } from "react";
import { useMsal } from "@azure/msal-react";
import { InteractionStatus } from "@azure/msal-browser";
const { instance, accounts, inProgress } = useMsal();
const [loading, setLoading] = useState(false);
const [apiData, setApiData] = useState(null);
useEffect(() => {
if (!loading && inProgress === InteractionStatus.None && accounts.length > 0) {
if (apiData) {
// Skip data refresh if already set - adjust logic for your specific use case
return;
}
const tokenRequest = {
account: accounts[0], // This is an example - Select account based on your app's requirements
scopes: ["User.Read"]
}
// Acquire an access token
instance.acquireTokenSilent(tokenRequest).then((response) => {
// Call your API with the access token and return the data you need to save in state
callApi(response.accessToken).then((data) => {
setApiData(data);
setLoading(false);
});
}).catch(async (e) => {
// Catch interaction_required errors and call interactive method to resolve
if (e instanceof InteractionRequiredAuthError) {
await instance.acquireTokenRedirect(tokenRequest);
}
throw e;
});
}
}, [inProgress, accounts, instance, loading, apiData]);
if (loading || inProgress === InteractionStatus.Login) {
// Render loading component
} else if (apiData) {
// Render content that depends on data from your API
}

点击这里阅读更多

你可能错过了handleRedirectPromise…一旦重定向完成,承诺应该捕获帐户…如果没有,尝试另一个aquireSilentToken在下面的承诺中捕获它。

instance.handleRedirectPromise().then(resp => {
if (resp && resp.account) instance.setActiveAccount(resp.account);
});

最新更新