![](/img/trans.png)
[英]React MSAL Library msal-react : Issue in persisting the login session in different user-policies B2C application
[英]How can I retrieve a token from msal-react on initial callback?
我正在使用 msal-react 嘗試在我的應用程序上對用戶進行身份驗證,但是最初重定向回我的應用程序似乎沒有提供令牌。 如果我在回調后刷新頁面,應用程序將按預期工作。 我已正確設置 Azure AD,並且我已驗證我可以在 Postman 中獲得同一用戶的令牌。
目前我的 index.tsx 頁面是這樣的:
import { Configuration, PublicClientApplication } from "@azure/msal-browser";
import { MsalProvider } from "@azure/msal-react";
...
const configuration: Configuration = {
auth: {
authority: 'https://login.microsoftonline.com/organizations',
clientId: '<AppClientId>',
redirectUri: 'https://localhost:3000',
}
};
const pca = new PublicClientApplication(configuration);
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<MsalProvider instance={pca}>
<App />
</MsalProvider>
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
由於我想進行自動登錄而不是讓用戶單擊登錄按鈕,因此我嘗試從 App.tsx 文件進行登錄。 這是因為當應用程序最初加載時,我被重定向到 Azure 登錄頁面,我可以使用我的用戶名和密碼成功登錄。 但是當重定向發生時,由於帳戶仍然是空的,它會再次調用相同的 instance.loginRedirect 調用。 如前所述,當我刷新瀏覽器中的頁面時,帳戶已填充,並且我按預期顯示了該應用程序。
這是我對 App.tsx 的看法:
function Login(): React.ReactElement {
const { instance } = useMsal();
useEffect(() => {
const accounts = instance.getAllAccounts();
if (!accounts || accounts.length < 1) {
instance.loginRedirect({
scopes: ["profile", "openid"]
});
}
}, [instance]);
return (
<p>Signing in...</p>
);
}
function App(): React.ReactElement {
return (
<>
<AuthenticatedTemplate>
<Router>
<ThemeProvider theme={theme}>
... App Components ...
</ThemeProvider>
</Router>
</AuthenticatedTemplate>
<UnauthenticatedTemplate>
<Login />
</UnauthenticatedTemplate>
</>
);
}
當我查看商店時,我可以看到我有一個有效的訪問令牌,所以我一定是錯過了一個步驟
我還嘗試使用 inProgress 字符串來查看我是否可以檢測到不同的狀態以阻止第二次調用的發生,但這也沒有用。 除了我無法阻止我的應用程序第二次調用 loginRedirect 之外,一切似乎都在工作。
對此的任何幫助將不勝感激。
編輯:應該提到我得到的錯誤是“interaction_in_progress:交互當前正在進行中。請確保在調用交互式 API 之前已完成此交互。”
嘗試這個。
import { InteractionStatus } from "@azure/msal-browser";
...
const { instance, inProgress } = useMsal();
useEffect(() => {
if (inProgress === InteractionStatus.None && !isAuthenticated) {
instance.loginRedirect(loginRequest)
.catch(e => {
console.error(e);
});
}
});
在調用登錄重定向之前,您需要檢查 InteractionStatus。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.