Invoke-Restmethod在期望使用Powershell的json时返回text/html



正在使用的命令:

$Tenant = "tentant_id"
$ClientID = "application_id"
$ClientSecret = "application_password"
$Url = "http://login.microsoftonline.com/$Tenant/oauth2/v2.0/token"
$Body = @{
  'client_id' = $ClientID
  'scope' = "https://graph.microsoft.com/.default"
  'client_secret' = $ClientSecret
  'grant_type' = 'client_credentials'
}
Invoke-RestMethod -Method Post -Uri $Url -Body $Body -Verbose

实际结果:

VERBOSE: POST http://login.microsoftonline.com/<tenant_ID>/oauth2/v2.0/token with -1-byte payload
VERBOSE: received 17293-byte response of content type text/html; charset=utf-8
html
----
html

预期成果:

{
    "token_type": "Bearer",
    "expires_in": 3599,
    "ext_expires_in": 0,
    "access_token": "eyJ0eXAiOiJKV1Q......."
}

我错过了什么吗?出于某种原因,在Powershell中使用上述代码时,它会返回某种网页,而它应该提供令牌。使用 Chrome 扩展名 Postman,我能够使用相同的 url、客户端 ID、范围、客户端密钥和正文中的授权类型来构造 POST 请求,从而给出正确的响应。使用其中的访问令牌,然后我可以使用以下内容来获取正确的响应:

Invoke-RestMethod -Method Get -Headers @{Authorization = "Bearer $AccessToken"} -Uri https://graph.microsoft.com/v1.0/users/jsmith@example.com

这是 pastebin 输出$HtmlObject | 格式列表 * 的链接https://pastebin.com/KMMKDGut因为它太大了,无法在此处格式化为代码。

通常,当您返回对 JSON 或 SOAP 调用的 HTML 响应时,这意味着 IIS 真的很不高兴,并且返回了一个 IIS/ASP.net 错误页面。 在这种情况下,通常需要查看服务器本身的事件日志,以找出 IIS/ASP.Net 不高兴的原因。

感谢Marc LaFleur的建议,我和Fiddler一起看了一下这个请求。它显示了以下内容:

HTTP/1.1 302 Found
Location: https://login.microsoftonline.com:443/clientID/oauth2/v2.0/token
Server: Microsoft-IIS/8.5
client-request-id: 1d918059-ab39-4d41-8191-b0416d4f03f4
X-Powered-By: ASP.NET
Date: Wed, 10 Jan 2018 21:52:51 GMT
Content-Length: 209
<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="https://login.microsoftonline.com:443/clientID/oauth2/v2.0/token">here</a>.</h2>
</body></html>

显然,我所要做的就是将原始URL更改为https,这样它就不必重定向。不确定返回的 Html 对象中发生了什么,以及为什么我在 Fiddler 中没有看到它。

最新更新