如何让 Apex Restful 服务中的 access_token 首先从外部调用 GET/POST 方法?

How to get the access_token first in Apex Restful service to call GET/POST methods from outside?

我正在从 link 做 Salesforce trailhead:https://trailhead.salesforce.com/modules/apex_integration_services/units/apex_integration_webservices

在本教程中,他们使用 access_token 调用 GET 请求。 但是他们并没有指导我们如何获取access_token,这是从外部调用APEX Rest的重要步骤

我想做一些类似下面的事情,它告诉我错误:

https://ap5.salesforce.com/services/oauth2/token?client_id="3MVG9d8..z.hDcPJZPIzGJ5UZDuKCOqbH8CCGCPnmwQuRbwLZ_2f.thbqWMX82H7JRGx4
6VYyEkuwzQ9._ww5"&client_secret="1180508865211885204"&username="pXXXXXXXXXXXXXXX.com"&password="AgXXXXXXXX"&grant_type=password

您可能需要调用 api 来获取访问令牌。

这是我在 C# 中获取访问令牌的代码

async public static Task GetAccessTokenByUserNamePasswordAuthenticationFlowAsync(字符串用户名,字符串密码,字符串令牌,字符串 consumerKey,字符串 consumerSecret) {

        HttpClient authClient = new HttpClient();


        string sfdcConsumerKey = consumerKey;
        string sfdcConsumerSecret = consumerSecret;

        string sfdcUserName = username;
        string sfdcPassword = password;
        string sfdcToken = token;



        string loginPassword = sfdcPassword + sfdcToken;

        HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                {"grant_type","password"},
                {"client_id",sfdcConsumerKey},
                {"client_secret",sfdcConsumerSecret},
                {"username",sfdcUserName},
                {"password",loginPassword}
            }
             );
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; //tuanv2t: Salesforce has changed to use TLS 1.1 -> 
        //tuanv2t: Without, responseString will like this {"error":"unknown_error","error_description":"retry your request"}
        HttpResponseMessage message = await authClient.PostAsync("https://login.salesforce.com/services/oauth2/token", content);

        string responseString = await message.Content.ReadAsStringAsync();

        //JObject obj = JObject.Parse(responseString);
        //var oauthToken = (string)obj["access_token"];
        //var serviceUrl = (string)obj["instance_url"];

        var result = new GetAccessTokenResponse();
        result.HttpResponseMessage = message;
        //Convert json string into object
        var accessTokenAPI = JsonConvert.DeserializeObject<AccessTokenAPI>(responseString);

        if (accessTokenAPI != null)
        {
            result.AccessToken = new AccessTokenModel();
            result.AccessToken.AccessToken = accessTokenAPI.access_token;
            result.AccessToken.Id = accessTokenAPI.id;
            result.AccessToken.InstanceUrl = accessTokenAPI.instance_url;
            result.AccessToken.IssuedAt = accessTokenAPI.issued_at;
            result.AccessToken.Signature = accessTokenAPI.signature;
            result.AccessToken.TokenType = accessTokenAPI.token_type;
        }
        return result;

    }

可以在这里下载我所有的源代码示例(也包括 SOAP API) https://bitbucket.org/tuanv2t/salesforceapidemo

我现在理解了这个概念,感谢分享其他链接。

client_id, client_secret, username, password and grant_type 应该在 HTTP POST body 中发送,而不是在 header.

中发送
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setHeader('Content-Type','application/x-www-form-urlencoded');
req.setEndpoint('https://ap5.salesforce.com/services/oauth2/token');

String CLIENT_ID = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
String CLIENT_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXX';
String USERNAME = 'XXXXXXXXXXXXXX';
String PASSWORD = 'XXXXXXXXXXXXXX';

req.setBody('grant_type=password' + '&client_id='+CLIENT_ID + 
            '&client_secret='+CLIENT_SECRET + '&username='+USERNAME + '&password='+PASSWORD);

Http http = new Http();
HTTPResponse response = http.send(req);
System.debug('Body ' + response.getBody());
System.debug('Status ' + response.getStatus());
System.debug('Status code ' + response.getStatusCode());