我正在尝试通过我的应用程序中的 oauth 从 Salesforce 获取所有联系人。我收到远程服务器在我的回调页面上尝试通过API令牌网址获取访问令牌时返回错误:(400)错误请求。。甚至当我复制URL并直接粘贴到URL时,它给了我正确的数据。但无法获得访问令牌。
我使用以下方法获取访问令牌。请专家建议我在哪里做错了。同样的方法适用于Google和LinkedIn。
public async Task<TokenResponse> GetAccessToken(string code,string tokenUrl,string consumerKey,string consumerSecretKey,string redirecturl)
{
string responseFromServer = "";
var webRequest = WebRequest.Create(tokenUrl);
const string queryStringFormat = @"code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code";
string contents = string.Format(queryStringFormat
, code
, consumerKey
, consumerSecretKey
, redirecturl);
webRequest.Method = "POST";
byte[] postcontentsArray = Encoding.UTF8.GetBytes(contents);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postcontentsArray.Length;
using (Stream requestStream = webRequest.GetRequestStream())
{
requestStream.Write(postcontentsArray, 0, postcontentsArray.Length);
requestStream.Close();
WebResponse response = webRequest.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
responseFromServer = reader.ReadToEnd();
reader.Close();
responseStream.Close();
response.Close();
}
}
}
}
return JsonConvert.DeserializeObject<TokenResponse>(responseFromServer);
}
请帮我解决此问题。
答案 0 :(得分:1)
我没有问题地连接到Salesforce,但我使用的是HttpClient而不是WebRequest。
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{"grant_type", "password"},
{"client_id", _clientId},
{"client_secret", _clientSecret},
{"username", _userName},
{"password", _password}
}
);
using (var httpClient = new HttpClient())
{
var message =
await httpClient.PostAsync(_authorizationUrl, content).ConfigureAwait(false);
var responseString = await message.Content.ReadAsStringAsync().ConfigureAwait(false);
var obj = JObject.Parse(responseString);
var oauthToken = (string)obj["access_token"];
var serviceUrl = (string)obj["instance_url"];
}