You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React使用@azure/msal-react的loginPopup出现hash_empty_error求助

修复@azure/msal-react的hash_empty_error问题

问题场景

使用React版微软身份认证库(@azure/msal-react)调用loginPopup方法完成登录时,抛出hash_empty_error,错误提示哈希值为空,无法完成认证流程。

错误日志

authConfig.js:19  [Sun, 06 Oct 2024 17:36:03 GMT] : [019262e6-c629-7327-96d7-5a73bd4f352b] : msal.js.browser@3.24.0 : Error - The request has returned to the redirectUri but a fragment is not present. It's likely that the fragment has been removed or the page has been redirected by code running on the redirectUri page.
...
index.js:32  Error during authentication BrowserAuthError: hash_empty_error: Hash value cannot be processed because it is empty. Please verify that your redirectUri is not clearing the hash.

问题排查

1. 路由强制跳转干扰

App.js中存在一个触发频繁跳转的副作用钩子:

useEffect(() => {
  navigate(location.pathname);
}, [inProgress, accounts, navigate, location.pathname]);

loginPopup完成后,MSAL会在URL上追加包含认证信息的哈希片段,这个钩子会在MSAL处理哈希前强制跳转到当前路径,直接清除了哈希,导致MSAL无法解析认证结果。

2. 登录组件冗余的重定向流处理

登录组件(Basic.js)中的handleRedirectPromise是给**重定向登录流(loginRedirect)**设计的逻辑,而当前使用的是弹窗登录流(loginPopup),这段多余的代码会干扰弹窗流的正常回调流程。

修复方案

方案1:移除强制跳转的副作用钩子

删除App.js中这段触发不必要跳转的代码:

// 移除这段代码
useEffect(() => {
  navigate(location.pathname);
}, [inProgress, accounts, navigate, location.pathname]);

如果需要在登录状态变化时处理路由,改为仅在认证完成且无交互时触发:

useEffect(() => {
  if (isAuthenticated && inProgress === InteractionStatus.None) {
    // 如需根据角色跳转,逻辑移到登录成功后的handleSuccessfulLogin中,避免重复跳转
  }
}, [isAuthenticated, inProgress]);

方案2:移除登录组件中冗余的重定向处理

删除登录组件(Basic.js)中的handleRedirectPromise处理逻辑:

// 移除这段代码
useEffect(() => {
  console.log('in instance use effect , ');
  instance.handleRedirectPromise()
    .then((response) => {
      if (response) {
        console.log('Login response from handleRedirectPromise', response);
        handleSuccessfulLogin(response);
      }
    })
    .catch((error) => {
      console.error('Error handling redirect response', error);
    });
}, [instance]);

方案3:验证redirectUri配置一致性

确保authConfig.js中的redirectUri与Azure AD应用注册后台配置的重定向URI完全一致,弹窗流的redirectUri建议设置为登录页面本身,例如:

// authConfig.js示例
export const msalConfig = {
  auth: {
    redirectUri: `${window.location.origin}/authentication/sign-in`,
    // 其他配置...
  }
};

方案4:确认路由模式兼容性

如果使用react-router的createBrowserRouter,确保未启用hashMode,浏览器模式(browserRouter)与MSAL弹窗流兼容性更好,避免路由逻辑额外清除URL哈希。

验证修复步骤

  1. 重启应用,点击登录按钮触发loginPopup
  2. 登录完成后,观察URL是否短暂出现哈希片段,MSAL会自动处理并跳转
  3. 检查控制台是否正常输出loginResponse,并成功更新全局状态与路由跳转

内容的提问来源于stack exchange,提问作者vVv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 14:04:52