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

iOS平台MSAL集成AD登录时如何获取refreshToken

解决AD登录获取refreshToken的问题

核心配置检查

  • 确保应用注册时启用了offline_access权限:在Azure AD的应用注册中,API权限里添加Microsoft Graph的offline_access委托权限,并且完成管理员同意(如果是租户级应用)。这是获取refreshToken的前提,没有这个权限任何方法都拿不到。
  • 确认认证请求中包含offline_access范围:不管用哪种方式发起认证,必须在scope参数里加入offline_access,比如:
    const loginRequest = {
      scopes: ["user.read", "offline_access"] // 必须包含offline_access
    };
    

针对acquireToken/acquireTokenSilently的调整

  • 使用acquireToken时,确保请求的scope包含offline_access,并且登录会话是首次授权或者权限有更新的情况。首次授权用户同意后,refreshToken会随authToken一起返回。
  • acquireTokenSilently仅在已有有效refreshToken的情况下刷新token,如果之前没拿到过refreshToken,这个方法不会凭空生成。需要先通过带offline_access的授权流程获取到初始的refreshToken。

关键排查点

  • 检查授权流类型:隐式授权流不返回refreshToken,必须使用授权码流(Authorization Code Flow)或者混合流(Hybrid Flow)。如果之前用的是隐式流,需要切换到授权码流。
  • 确认应用类型配置:单页应用(SPA)在Azure AD中需要配置为SPA类型,并且使用授权码流(PKCE)才能获取refreshToken。

代码示例(MSAL.js v2)

const msalInstance = new msal.PublicClientApplication({
  auth: {
    clientId: "your-client-id",
    authority: "https://login.microsoftonline.com/your-tenant-id"
  }
});

// 登录并获取包含refreshToken的响应
async function loginAndGetTokens() {
  const loginResponse = await msalInstance.loginPopup({
    scopes: ["user.read", "offline_access"]
  });
  // 查看refreshToken
  console.log(loginResponse.account.refreshToken);
}

// 静默刷新获取新的authToken和refreshToken(如果有)
async function silentRefresh() {
  const account = msalInstance.getActiveAccount();
  const response = await msalInstance.acquireTokenSilently({
    account: account,
    scopes: ["user.read", "offline_access"]
  });
  console.log(response.refreshToken);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:52:07