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

React集成MSAL调用API时出现401权限错误求助

MSAL React调用本地API返回401错误求助

我在React项目中使用Microsoft的MSAL库,已完成前端(React)和后端(API)的Azure应用注册。当前在本地环境测试,API部署在本地服务器,流程如下:

  • 使用MSAL完成SSO登录
  • 利用登录获取的令牌调用API

登录功能正常,可通过Microsoft账号完成SSO登录,但调用API时传递登录获取的令牌却返回401错误。

相关代码

authConfig.js

const config = {
    auth: {
        clientId: "my-front-end-client-id",
        authority: "https://login.microsoftonline.com/my-tenant-id", 
        redirectUri: "http://localhost:3000/home", 
    },
    cache: {
        cacheLocation: "localStorage"
        storeAuthStateInCookie: false 
    },
    system: {
        loggerOptions: {
            loggerCallback: (level, message, containsPii) => {
                if (containsPii) {
                    return;
                }
                switch (level) {
                    case LogLevel.Error:
                        console.error(message);
                        return;
                    case LogLevel.Info:
                        console.info(message);
                        return;
                    case LogLevel.Verbose:
                        console.debug(message);
                        return;
                    case LogLevel.Warning:
                        console.warn(message);
                        return;
                }
            },
            piiLoggingEnabled: false 
        }
    }
};

const loginRequest = {
    scopes: ["user.read"] 
};

export { config, loginRequest };

Login.js

const handleLogin = async () => {
    try {
      await instance.loginPopup(loginRequest);
      navigate("/home");
    } catch (error) {
      console.error("Error logging in:", error);
    }
};

LandingPage.js (首页)

const { instance, accounts } = useMsal();
const [accessToken, setAccessToken] = useState(null);
var request = {
    scopes : ['api://backend-client-id/myapp.information.read']
}

useEffect(() => {
    const getToken = async () => {
        try {
            const response = await instance.acquireTokenSilent({
                request,
                account: accounts[0]
            });

            setAccessToken(response.accessToken);
            console.dir(response);
        } catch (error) {
            console.error(error);
        }
    };

    getToken();
}, [instance, accounts]);

const handleCallApi = async () => {
    try {
        if (accessToken) {
            const apiResponse = await callApi(accessToken);
            console.log(apiResponse);
        } else {
            console.error("Access token not available");
        }
    } catch (error) {
        console.error("Error calling API:", error);
    }
};

Azure应用注册设置

前端应用注册

  • 认证:配置重定向URI为 http://localhost:3000/home 和 http://localhost:3000/
  • API权限:已配置对应权限(截图略)

后端(API)应用注册

  • 认证:Web重定向URI为 http://localhost:3000/home,已勾选隐式授予和混合流下的访问令牌与ID令牌
  • API权限:已配置对应权限(截图略)
  • 公开API:作用域为 myapp.information.readall,已添加前端客户端ID
  • 应用角色:值为 myapp.information.read

我对认证流程不太熟悉,卡在此问题多时,排查过React代码未发现问题,尝试修改Azure应用注册设置但仍未解决,恳请帮助。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:13:09