@azure/msal-react v3中Authorization code返回undefined的问题求助
问题
我需要将Authorization Code发送至后端,以此获取微软用户的refresh token和access token。目前使用@azure/msal-react库处理弹窗与重定向,该库能正确获取access token及其他凭据,但返回的code始终为undefined。请问是否可以通过该库获取Authorization Code?
相关代码
登录处理函数:
const handleMicrosoftLogin = async () => { const loginRequest = { scopes: ['user.read', 'offline_access'] // Add the necessary scopes } try { const res = await instance.acquireTokenPopup(loginRequest) console.log(res) // const user: MsJWTPayload = jwtDecode(res.idToken) // setCurrentMailbox({ // accessToken: res.accessToken, // name: user?.name || '', // email: user?.preferred_username || '' // }) // setShowPasswordInput(true) } catch (error) { console.error('Login failed:', error) } }
实例配置:
export const msalConfig: Configuration = { auth: { clientId: import.meta.env.VITE_MICROSOFT_AUTH_CLIENT_ID, authority: 'https://login.microsoftonline.com/679a768c-6cda-4071-ae37-5de31aeb7629', redirectUri: window.location.href } } export const pca = new PublicClientApplication(msalConfig)
返回响应示例
{ "authority": "https://login.microsoftonline.com/common/", "uniqueId": "00000000-0000-0000-831a-ed4248869963", "tenantId": "9188040d-6c67-4c5b-b112-36a304b66dad", "scopes": [ "User.Read", "openid", "profile" ], "code": undefined, "idToken": "abcdefXXXXX", "accessToken": "XXXXXX-----", ...rest of ms auth data }
解答
可以通过@azure/msal-react获取Authorization Code,但你当前使用的acquireTokenPopup属于隐式/混合授权流的调用逻辑,不会返回授权码。要获取Authorization Code,需切换到授权码流(Authorization Code Flow),具体调整如下:
修改登录请求逻辑
替换acquireTokenPopup为loginPopup(或loginRedirect),并明确指定responseType: "code",触发授权码流流程:const handleMicrosoftLogin = async () => { const loginRequest = { scopes: ['user.read', 'offline_access'], responseType: "code" // 关键配置,指定返回授权码 } try { const res = await instance.loginPopup(loginRequest); console.log(res); // 此时res中会包含有效的code字段 } catch (error) { console.error('Login failed:', error); } }确认Azure AD应用配置
在Azure门户的应用注册后台,确保已开启授权码流支持:- 进入应用注册页面 -> 认证 -> 添加平台 -> 选择"单页应用(SPA)"
- 确认"授权码流"选项已勾选(新版本应用注册默认已开启)
关键注意事项
- 授权码
code为一次性凭证,需立即发送至后端,由后端调用微软token端点交换refresh token和access token - 后端交换时需使用应用的
clientSecret(或证书),前端绝对不能存储clientSecret - 你的请求中已包含
offline_accessscope,这是获取refresh token的必要条件,无需修改
- 授权码
内容的提问来源于stack exchange,提问作者Vedant Singh
相关产品推荐
相关产品推荐

