下面的代码完全正常工作,并从azure返回所需的访问令牌,但如果我试图从节点js或postman执行相同的功能,它会提示错误:
{“error”:“invalid_client”,“error_description”:“AADSTS70002:验证凭据时出错.AADSTS50012:提供了无效的客户端密码。\ r \ nTrace ID:922f61ca-0349-47fc-8c60-326cb29b2000 \ r \ n相关ID:3d39e54d -deb2-49de-84c0-9705e2977c2e \ r \ n时间戳:2017-07-18 14:29:14Z“,”error_codes“:[70002,50012],”timestamp“:”2017-07-18 14:29:14Z ”, “trace_id的”: “922f61ca-0349-47fc-8c60-326cb29b2000”, “CORRELATION_ID”: “3d39e54d-deb2-49de-84c0-9705e2977c2e”}
但是在java环境中同样可以很好地工作
HttpPost httpPost = new HttpPost("https://login.microsoftonline.com/" + environment.getTenantId() + "/oauth2/token");
List<NameValuePair> nameValuePairs = new ArrayList(3);
nameValuePairs.add(new BasicNameValuePair("grant_type", "client_credentials"));
nameValuePairs.add(new BasicNameValuePair("client_id", environment.getClientId()));
nameValuePairs.add(new BasicNameValuePair("client_secret", environment.getClientSecret()));
nameValuePairs.add(new BasicNameValuePair("resource", "https://graph.windows.net"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = httpClient.execute(httpPost);
String postResponse = EntityUtils.toString(response.getEntity());
String startPoint = "\"access_token\":\"";
int startIndex = postResponse.indexOf(startPoint);
int adjustPoint = startIndex + startPoint.length();
String objectId = postResponse.substring(adjustPoint);
int tokenLength = objectId.length();
String accessToken = objectId.substring(0, tokenLength - 2);
return accessToken;
对我来说,HttpClient
API始终运行良好。我认为您使用的类不能正确编码值。
// Static field within class to share the same client instance
private static HttpClient Client = new HttpClient();
public async Task<string> GetAccessTokenAsync()
{
//Get the environment variable from somewhere
var request = new HttpRequestMessage(HttpMethod.Post, "https://login.microsoftonline.com/" + environment.getTenantId() + "/oauth2/token");
var keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
keyValues.Add(new KeyValuePair<string, string>("client_id", environment.getClientId()));
keyValues.Add(new KeyValuePair<string, string>("client_secret", environment.getClientSecret()));
keyValues.Add(new KeyValuePair<string, string>("resource", "https://graph.windows.net"));
request.Content = new FormUrlEncodedContent(keyValues);
HttpResponseMessage response = await Client.SendAsync(request);
string json = await response.Content.ReadAsStringAsync();
JObject tokenResponse = JObject.Parse(json);
string accessToken = tokenResponse["access_token"];
return accessToken;
}