Azure访问令牌无法正常工作

问题描述 投票:0回答:1

下面的代码完全正常工作,并从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;
.net node.js azure azure-web-sites azure-active-directory
1个回答
0
投票

对我来说,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;
}
© www.soinside.com 2019 - 2024. All rights reserved.