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

MSAL loginPopup生产环境报BrowserAuthError: user_cancelled问题求助

MSAL loginPopup生产环境报user_cancelled错误,开发环境正常

问题描述

生产环境(前端构建后部署)中,用户点击登录按钮触发await instance.loginPopup(loginRequest)时,控制台抛出错误:

BrowserAuthError: user_cancelled: User cancelled the flow and popup for login is displayed.

该问题仅出现在生产环境,开发环境(前端3000端口、后端4151端口)弹窗登录完全正常,且loginRedirect在两种环境下均能正常工作。

相关代码与配置

登录逻辑代码

const handleLogin = async () => {
        try {
          await instance.loginPopup(loginRequest);
            navigate("/");
        } catch (error) {
            dispatch(
                setUserSnackMessage({ message: "Unexpected error during login.", status: true, type: 
  ISnackMessageStyle.error })
            );
            console.error("Login error:", error);
        }
    };

登录请求配置

export const loginRequest = {
    scopes: ["api://backed_id/all"],
};

环境配置

开发环境:

{
    "server_url": "http://localhost:4151",
    "FULL_URL": "http://localhost:3000"  // redirectUri, postLogoutRedirectUri
}

部署构建后:

{
    "server_url": "",
    "FULL_URL": "http://localhost:4151"
}

MSAL配置

export const msalConfig = {
    auth: {
        clientId: "client_id",
        authority: "https://login.microsoftonline.com/*****.onmicrosoft.com",
        redirectUri: FULL_URL,
        postLogoutRedirectUri: FULL_URL,
        clientCapabilities: ["CP1"],
    },
    cache: {
        cacheLocation: "localStorage",
        storeAuthStateInCookie: false,
    },
    system: {
        loggerOptions: {
            loggerCallback: (level: any, message: any, containsPii: any) => {
                if (!containsPii) {
                    console.log(`MSAL: ${message}`);
                }
            },
            // logLevel: LogLevel.Verbose,
            piiLoggingEnabled: false,
        },
        navigateToLoginRequestUrl: false,
    },
};

MSAL错误日志

MSAL: [Fri, 20 Dec 2024 06:17:30 GMT] : [] : @azure/msal-react@2.2.0 : Info - MsalProvider - msal:loginStart results in setting inProgress from none to login
MSAL: [Fri, 20 Dec 2024 06:17:30 GMT] : [0193e2b6-c89f-7271-97e5-059bfc9896e6] : msal.js.browser@3.27.0 : Error - PopupHandler.monitorPopupForHash - window closed
Login error: BrowserAuthError: user_cancelled: User cancelled the flow.
at gN (BrowserAuthError.ts:366:12)
at PopupClient.ts:561:25
MSAL: [Fri, 20 Dec 2024 06:17:30 GMT] : [] : @azure/msal-react@2.2.0 : Info - MsalProvider - msal:loginFailure results in setting inProgress from login to none
MSAL.js (@azure/msal-browser)
MSAL React (@azure/msal-react)

解决方案

1. 排查浏览器弹窗拦截

  • 确认handleLogin是直接绑定到用户点击事件,无额外异步延迟(如先调用API再触发loginPopup,会被浏览器判定为非用户主动操作)
  • 测试时手动允许当前域名的弹窗权限,排除拦截因素

2. 验证redirectUri一致性

  • 检查Azure AD应用注册的重定向URI列表,确保已添加生产环境的http://localhost:4151,且类型为单页应用(SPA)
  • 确认生产环境构建后redirectUri实际值正确,避免环境变量替换失败
  • 若前端与后端部署在不同端口,将FULL_URL改为前端实际部署地址

3. 调整MSAL缓存配置

生产环境下开启Cookie存储认证状态,解决跨域/上下文丢失问题:

cache: {
    cacheLocation: "localStorage",
    storeAuthStateInCookie: true, // 修改为true
},

4. 优化弹窗触发时机

添加短暂延迟确保弹窗在用户点击上下文内触发:

const handleLogin = async () => {
        try {
          await new Promise(resolve => setTimeout(resolve, 100)); // 添加延迟
          await instance.loginPopup(loginRequest);
            navigate("/");
        } catch (error) {
            // 错误处理逻辑
        }
    };

5. 配置弹窗属性

指定弹窗尺寸与位置,降低被拦截概率:

await instance.loginPopup({
    ...loginRequest,
    popupWindowAttributes: {
        width: 600,
        height: 600,
        left: window.screen.width / 2 - 300,
        top: window.screen.height / 2 - 300
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 10:09:58