4

我正在尝试使用以下代码列出使用 Office 365 统一 API 的用户:

$TenantID = "xxx"
$F_ClientID = "yyy"
$F_ClientSecret = "zzz"

Add-Type @'
using System;
public class OAuthContext{
    public string AccessToken{get;set;}
    public string TokenType{get;set;}
    public string ExpiresIn{get;set;}
    public string RefreshToken{get;set;}
}
'@

$Uri = "https://login.microsoftonline.com/$($TenantID)/oauth2/token"
$ContentType = 'application/x-www-form-urlencoded'
$Headers = @{}
$Body = [System.Text.Encoding]::UTF8.GetBytes('grant_type=client_credentials&client_id='+$F_ClientID+'&client_secret='+$F_Clie    ntSecret+'&resource"=https://graph.microsoft.com')
$Response = Invoke-RestMethod -Method POST -Uri $Uri -Headers $Headers -ContentType $ContentType -Body $Body
$Response

$Context = New-Object OAuthContext
$Context.AccessToken = $Response.access_token
$Context.ExpiresIn = $Response.expires_in
$Context.RefreshToken = $Response.refresh_token
$Context.TokenType = $Response.token_type
$Context

$Headers = @{}
$Headers.Add('Authorization',$Context.TokenType + ' ' + $Context.AccessToken)
$Headers

$Uri = "https://graph.microsoft.com/v1.0/users"

Invoke-RestMethod -Method GET -Uri $Uri -Headers $Headers

从结果中可以看出,访问令牌似乎已成功生成。但是在尝试列出用户时,我收到以下错误:

Invoke-RestMethod : {
"error": {
"code": "InvalidAuthenticationToken",
"message": "CompactToken parsing failed with error code: -2147184105",
"innerError": {
  "request-id": "067c7044-0c59-4a39-86ac-b89e6b13229c",
  "date": "2016-02-12T17:09:56"
}
}
}
At line:41 char:1
+ Invoke-RestMethod -Method GET -Uri $Uri -Headers $Headers
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation:     (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

我真的不知道我在这里做错了什么!谢谢你的帮助!

4

3 回答 3

6

响应实际上表明访问令牌未成功生成或传递给图形端点。Microsoft Graph 无法将其解析为 JWT 令牌,因此尝试将其作为 Microsoft 帐户/Live Id 紧凑令牌进行处理,但也失败了。请检查您从调用 login.microsoftonline.com 获得的响应,以及传递给 graph.microsoft.com 的令牌是否是有效的 JWT 令牌。

于 2016-02-18T00:38:47.717 回答
0

如果您发送的客户端密码与编码时页面的结果匹配,您能否检查此页面?

收件人在查看'application / x-www-form-urlencoded'时会解码url,如果你的客户端密码编码不好,某人的字符会消失。(这是我的问题)

我使用了这段代码并且它有效

于 2019-05-15T09:11:49.903 回答
-1

我建议首先使用图形资源管理器工具测试您发送到图形 API 的查询。然后在你的 PS 脚本中模仿相同的请求。

https://graphexplorer2.azurewebsites.net

于 2016-02-15T20:14:28.670 回答