遵循MSAL React官方教程时POST oauth2/v2.0/token返回400错误
问题现象
- 参照Azure官方
ms-identity-javascript-react-tutorial仓库中1-Authentication/2-sign-in-b2c示例项目的README文档操作,未找到相关问题说明;下载示例项目后按照教程自定义修改authConfig.js配置,甚至删除除登录策略外的所有配置项,项目仍无法正常运行。 - 项目可正常跳转至自建Azure AD B2C登录页面,配置重定向URI后可正常回跳至
localhost:3000,但页面无法识别用户为已认证状态,控制台抛出如下错误:
FetchClient.ts:58 POST https://<domain>.b2clogin.com/<domain>.onmicrosoft.com/b2c_1_sign_in/oauth2/v2.0/token 400 (Bad Request)
- 示例自带的默认配置可正常运行,始终无法定位配置错误点。
排查时提供的配置内容
以下是authConfig.js中b2cPolicies与msalConfig的配置内容:
export const b2cPolicies = { names: { signUpSignIn: "B2C_1_Sign_in" }, authorities: { signUpSignIn: { authority: "https://<domain>.b2clogin.com/<domain>.onmicrosoft.com/B2C_1_Sign_in", } }, authorityDomain: "<domain>.b2clogin.com" } /** * Configuration object to be passed to MSAL instance on creation. * For a full list of MSAL.js configuration parameters, refer to official MSAL documentation */ export const msalConfig = { auth: { clientId: "<ID>", // This is the ONLY mandatory field that you need to supply. authority: b2cPolicies.authorities.signUpSignIn.authority, // Use a sign-up/sign-in user-flow as a default authority knownAuthorities: [b2cPolicies.authorityDomain], // Mark your B2C tenant's domain as trusted. redirectUri: "/", // Points to window.location.origin. You must register this URI on Azure Portal/App Registration. postLogoutRedirectUri: "/", // Indicates the page to navigate after logout. navigateToLoginRequestUrl: false, // If "true", will navigate back to the original request location before processing the auth code response. }, cache: { cacheLocation: "sessionStorage", // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs. storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge }, 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; } } } } };
问题根因与解决方案
问题根源为Azure AD B2C中的应用注册清单配置有误:React这类运行在浏览器端的单页应用属于公共客户端,兑换授权码获取token时不需要携带客户端密钥。如果应用清单中关闭了公共客户端流开关,服务端会将当前应用识别为机密客户端,强制要求请求携带client_secret,最终导致token接口返回400错误。
修复操作步骤:
- 登录Azure Portal,进入对应Azure AD B2C租户的应用注册页面,打开当前项目使用的应用注册条目
- 进入「清单」编辑页,找到
allowPublicClient字段,将其值修改为true - 保存清单修改,清空浏览器站点缓存后重新测试登录流程即可正常识别登录状态。
内容的提问来源于stack exchange,提问作者JoeD
相关产品推荐
相关产品推荐

