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

联合登录后如何从AWS Cognito获取Salesforce访问令牌

问题:从AWS Cognito提取Salesforce身份提供商的访问令牌/刷新令牌

我已在应用中配置AWS Cognito,将Salesforce作为外部身份提供商(IDP)实现用户登录,当前流程如下:

用户被重定向至Cognito默认登录UI,可选择Salesforce作为登录选项。
选择Salesforce后,Cognito向Salesforce发送认证请求。
用户登录Salesforce后,Salesforce将授权码返回给Cognito。
Cognito用该授权码换取令牌,随后携带Cognito码将用户重定向回我的应用。
我通过该Cognito码从Cognito获取JWT。

现在需要使用Cognito从Salesforce获取的令牌调用Salesforce API,但不清楚如何从Cognito中提取Salesforce访问令牌或刷新令牌。尝试配置了Pre token generation Lambda触发器,但仍无法获取Salesforce的access_token或refresh_token。


可行解决方案

1. 调用Cognito用户池API提取令牌

Cognito会将外部IDP的令牌存储在用户身份属性中,可通过GetUser(已认证用户调用)或AdminGetUser(管理员权限调用)接口获取。在返回结果的UserAttributes中,查找identities属性,解析后即可提取Salesforce的令牌信息。

示例Node.js代码:

const { CognitoIdentityProviderClient, GetUserCommand } = require("@aws-sdk/client-cognito-identity-provider");

const client = new CognitoIdentityProviderClient({ region: "你的AWS区域" });
const command = new GetUserCommand({
  AccessToken: "用户的Cognito访问令牌"
});

const response = await client.send(command);
const identityAttr = response.UserAttributes.find(attr => attr.Name === "identities");
if (identityAttr) {
  const idpData = JSON.parse(identityAttr.Value);
  const sfIdentity = idpData.find(item => item.providerName === "Salesforce");
  if (sfIdentity) {
    const sfAccessToken = sfIdentity.accessToken;
    const sfRefreshToken = sfIdentity.refreshToken; // 仅当Salesforce返回时存在
    console.log("Salesforce访问令牌:", sfAccessToken);
  }
}

2. 配置Cognito与Salesforce的令牌传递规则

  • 在Salesforce连接应用中,确保勾选Refresh Token权限范围,并设置合理的令牌过期时间;
  • 在Cognito用户池的Salesforce IDP配置页,开启Enable Token Transfer选项,确保Cognito将Salesforce的令牌同步到用户属性中。

3. 使用Post Authentication Lambda触发器存储令牌

Pre token generation触发器仅用于修改Cognito自身的JWT,而Post Authentication触发器在用户认证完成后触发,可直接获取外部IDP的令牌。你可以在该触发器中将Salesforce令牌写入用户自定义属性,后续通过GetUser接口读取。

示例Lambda代码片段:

exports.handler = async (event) => {
  const identities = event.request.userAttributes.identities;
  if (identities) {
    const idpData = JSON.parse(identities);
    const sfIdentity = idpData.find(item => item.providerName === "Salesforce");
    if (sfIdentity) {
      event.response = {
        userAttributes: {
          "custom:sf_access_token": sfIdentity.accessToken,
          "custom:sf_refresh_token": sfIdentity.refreshToken || ""
        }
      };
    }
  }
  return event;
};

4. 检查Salesforce连接应用的权限范围

确保在Salesforce连接应用中请求了必要的权限范围,比如:

  • api:用于调用Salesforce REST API
  • refresh_token:获取刷新令牌
  • openid:支持OpenID Connect认证

只有请求了这些范围,Salesforce才会返回对应令牌,Cognito才能获取并存储。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 09:05:00