(400) Неверный запрос: получить AccessToken из ошибки Salesforce: "invalid_grant" - PullRequest
1 голос
/ 08 января 2020

Я использую функцию azure с кодом ниже - все работает нормально, когда я запускаю azure fucntion локально, но после развертывания я получаю ошибку ниже

{"error": "invalid_grant", "error_description": "сбой аутентификации"}

Код функции -

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.SystemDefault | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "tokenURL");
                var keyValues = new List<KeyValuePair<string, string>>();
                keyValues.Add(new KeyValuePair<string, string>("grant_type", "password"));
                keyValues.Add(new KeyValuePair<string, string>("client_id", "clientID"));
                keyValues.Add(new KeyValuePair<string, string>("client_secret", "clientSecret"));
                keyValues.Add(new KeyValuePair<string, string>("username", "userName"));
                keyValues.Add(new KeyValuePair<string, string>("password", "password"));

                request.Content = new FormUrlEncodedContent(keyValues);
                request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                HttpResponseMessage response = await httpClient.SendAsync(request);

                    string respContent = await response.Content.ReadAsStringAsync();
                    var oauthResponse = JsonConvert.DeserializeObject<Dictionary<string, string>>(respContent);
                    string token = oauthResponse["access_token"];

Требуются ли от Salesforce какие-либо другие настройки?

Изменить подключенное приложение: (Изменить политики) Снять ограничения IP-адресов

Разрешено пользователям "Все пользователи могут самостоятельно авторизоваться"

1 Ответ

2 голосов
/ 08 января 2020

Вот что мы имеем в наших Azure функциях, которые работают как положено. ISalesforceConfigSettings не из какой-либо библиотеки, это наш собственный рукописный интерфейс, реализация которого считывает значения из переменных окружения.

    /// <summary>
    /// Gets the Salesforce access token given the client_id, secret, username and password.
    /// </summary>
    /// <param name="log">Tracewriter log</param>
    /// <param name="_settings">ISalesforceConfigSettings _settings</param>
    /// <returns>A Salesforce access token</returns>
    private async string GetSalesforceAccessToken(TraceWriter log, ISalesforceConfigSettings _settings)
    {
        var httpClient = new HttpClient();

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;

        // Create Request Body
        var formContent = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("client_id", _settings.SalesforceClientId),
            new KeyValuePair<string, string>("client_secret", _settings.SalesforceClientSecret),
            new KeyValuePair<string, string>("username", _settings.SalesforceUserName),
            new KeyValuePair<string, string>("password", _settings.SalesforcePassword),
            new KeyValuePair<string, string>("grant_type", _settings.SalesforceGrantType)
        });

        try
        {
            // Call to get access token
            var loginResponse = await httpClient.PostAsync(_settings.SalesforceLoginUrl, formContent);
            var loginResponseString = await loginResponse.Content.ReadAsStringAsync();

            // Log Login Response
            log.Info(loginResponseString);

            // Extract Access Token
           return JsonConvert
                .DeserializeObject<SalesforceLoginResponse>(loginResponseString)
                .AccessToken;
        }
        catch (Exception ex)
        {
            log.Error(ex.Message);
            throw;
        }
    }

На всякий случай, если вам интересно, что такое класс SalesforceLoginResponse ...

using Newtonsoft.Json;

namespace Models.Salesforce
{
    public class SalesforceLoginResponse
    {
        [JsonProperty("access_token")]
        public string AccessToken { get; set; }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...