同一Salesforce组织内Flow Action调用REST服务的认证方法
解决方案
方案1:在Invocable Method中获取Session ID调用内部REST服务
这是最轻量化的方案,无需额外配置Named Credentials等组件:
- 在你的Invocable Apex类中,直接通过
UserInfo.getSessionId()获取当前用户的Session ID(Flow中无法直接获取,但Apex Invocable方法可以拿到)。 - 构造内部REST服务的请求URL:用
URL.getSalesforceBaseUrl().toExternalForm()拿到当前组织的Base URL,再拼接上目标包的REST路径(比如/services/apexrest/ns__MyRestEndpoint,ns__是包的命名空间)。 - 发送HTTP请求时,在Header中添加
Authorization: Bearer {sessionId}完成认证。
示例代码:
@InvocableMethod(label='调用内部REST服务' description='调用已安装包的REST接口') public static List<ResponseWrapper> invokeRestService(List<RequestWrapper> requests) { List<ResponseWrapper> responses = new List<ResponseWrapper>(); String sessionId = UserInfo.getSessionId(); String baseUrl = URL.getSalesforceBaseUrl().toExternalForm(); String restEndpoint = baseUrl + '/services/apexrest/ns__MyServicePath'; // 替换为实际的包REST路径 for (RequestWrapper req : requests) { Http http = new Http(); HttpRequest request = new HttpRequest(); request.setEndpoint(restEndpoint); request.setMethod('POST'); // 按需替换为GET/PUT等REST方法 request.setHeader('Authorization', 'Bearer ' + sessionId); request.setHeader('Content-Type', 'application/json'); request.setBody(JSON.serialize(req.payload)); try { HttpResponse res = http.send(request); ResponseWrapper resp = new ResponseWrapper(); resp.success = res.getStatusCode() == 200; resp.responseBody = res.getBody(); responses.add(resp); } catch (Exception e) { responses.add(new ResponseWrapper(false, '请求失败:' + e.getMessage())); } } return responses; } // 定义请求/响应包装类 public class RequestWrapper { @InvocableVariable(label='请求体' required=true) public Map<String, Object> payload; } public class ResponseWrapper { @InvocableVariable(label='是否成功') public Boolean success; @InvocableVariable(label='响应内容') public String responseBody; }
方案2:简化版Named Credential配置(可选)
如果不想在代码中硬编码Endpoint路径,可以用Named Credential,但无需复杂的外部认证配置:
- 创建External Credential,选择Identity Type为
Named Principal,Authentication Provider选Salesforce,配置对应权限集(确保有调用目标REST服务的权限)。 - 创建Named Credential,关联上述External Credential,设置Endpoint为目标REST路径(比如
/services/apexrest/ns__MyRestEndpoint),勾选“Allow Merge Fields in HTTP Header”和“Allow Merge Fields in HTTP Body”。 - 在Invocable方法中,直接用Named Credential的别名作为Endpoint(比如
callout:My_Named_Credential),Salesforce会自动处理认证,无需手动添加Session ID。
这种方式能把配置和代码解耦,但比方案1多了几步配置操作。
结论
不需要强制配置全套复杂的Authentication Provider组件。优先选方案1,仅在需要解耦配置与代码时考虑方案2。
内容的提问来源于stack exchange,提问作者mtbIt
相关产品推荐
相关产品推荐

