Username/password 具有 Salesforce 命名凭据的 JWT

Username/password JWT with Salesforce Named Credentials

我需要与使用我不熟悉的身份验证流程的服务集成,我想知道我可以使用命名凭据吗?

流程要求我首先通过在 JSON 正文中传递用户名和密码来获取 JWT 令牌。然后我可以将其用作常规不记名令牌。

  1. 获取令牌,其中returns{"securityToken": "TOKEN"}
curl --request POST \
  --url https://SERVICE_URL/token \
  --header 'Content-Type: application/json' \
  --data '{
    "Username": "USERNAME",
    "Password": "PASSWORD"
}'
  1. 调用安全端点
curl --request GET \
  --url https://SERVICE_URL/record \
  --header 'Authorization: Bearer TOKEN'

这是一个常见的身份验证流程吗?如果是,是否有一个通用的名称?

我可以在这种流程中使用 Salesforce 命名凭据吗?还是我需要手动调出令牌?

命名凭据不能用于处理此身份验证流程,但可以利用该功能获取令牌,而无需借助自定义设置之类的方法来存储用户名和密码。

  1. 创建一个专门用于获取令牌的命名凭据。

    Property Value Notes
    Label SERVICE Token Request Naming intends to specify that this is only for the token.
    URL https://SERVICE_URL/token Again, very specific to just the token call.
    Identity Type Named Principal This particular example uses the same username/password for all users.
    Authentication Protocol Password Authentication
    Username USERNAME The username required for the token request.
    Password PASSWORD The password required for the token request.
    Generate Authorization Header false If enabled, Salesforce will generate an authorization header, but the external service does not want it. The external service expects the username and password as separate properties in JSON.
    Allow Merge Fields in HTTP Body true Enabling this will allow usage of the username & password fields in apex.
  2. 匿名顶点

HttpRequest req = new HttpRequest();
req.setEndpoint('callout:SERVICE_Token_Request');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody('{"Username":"{!HTMLENCODE($Credential.Username)}",' +
            '"Password":"{!HTMLENCODE($Credential.Password)}"}');


Http http = new Http();
HTTPResponse res = http.send(req);
Map<String, Object> response = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
String securityToken = (String)response.get('securityToken');
System.debug(securityToken); // TOKEN