MSAL React的 useMsalAuthentication在 Safari上导致无限循环—— interaction_in_progress已失效
问题描述
我在一个React + Vite应用中,使用 @azure/msal-react 与 @azure/msal-browser v4.28.1。认证在Chrome和 Firefox上工作正常,但 Safari 会进入被阻止的状态:
errorCode: "interaction_in_progress"
errorMessage: "Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API. For mor…"
我使用重定向的MSAL行为,但没有发生重定向处理。 事实上,我已经使用正确的访问令牌完成连接。
错误指向使用useMsalAuthentication的 App组件。
代码
authConfig.ts
export const msalConfig: Configuration = {
auth: {
clientId: "...",
authority: "https://login.microsoftonline.com/...",
redirectUri: window.location.origin,
navigateToLoginRequestUrl: false,
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true,
},
};
export const loginRequest = {
scopes: [],
};
App.tsx
const App = () => {
const navigate = useNavigate();
const { accounts, instance } = useMsal();
const { login, result, error } = useMsalAuthentication(
InteractionType.Redirect,
loginRequest
);
useEffect(() => {
if (error) {
login(InteractionType.Redirect, loginRequest);
}
}, [error, login, result]);
return (
<>
<AuthenticatedTemplate>
<AppRoutes />
</AuthenticatedTemplate>
<UnauthenticatedTemplate>
<p>Unauthenticated</p>
</UnauthenticatedTemplate>
</>
);
};
解决方案
我已经能够重现该行为并给出修复:
简短结论:
这是一个Safari +基于Cookie的瞬态状态问题;
原因
当storeAuthStateInCookie = true时,MSAL会在重定向登录过程中把临时交互状态写入Cookie。 在Safari上,由于ITP(智能跟踪防护)/ Cookie的处理,这些Cookie在重新加载时可能变得不一致。 按下F5后,MSAL可能仍然看到一个交互标记(类似interaction_in_progress的状态),因此useMsalAuthentication会再次尝试、再次抛出异常,你的effect会重新触发登录,形成循环。
- 清除Cookies只会生效一次,因为它移除了过时的交互Cookie状态,但重新加载可能会重新创建同样的循环条件。
实际上,MSAL的 Cookies已经损坏。
针对你的情况的推荐配置:
将storeAuthStateInCookie移除或设为false即可停止循环。
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: false
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。