【问题标题】:Receive 401 error when try to retrieve Office 365 Audit log with MS Graph API with PowerShell尝试使用 PowerShell 使用 MS Graph API 检索 Office 365 审核日志时收到 401 错误
【发布时间】:2018-10-05 16:36:35
【问题描述】:

我正在尝试检索审核日志以跟踪用户许可证分配更改。 这是我在 MS Graph Explorer 中使用的 URI。它在那里工作得很好,我可以从中获取我想要的数据。

https://graph.microsoft.com/beta/auditLogs/directoryAudits?$filter=activityDisplayName eq 'Update user'

但是,当我尝试使用使用完全相同的 Office 365 凭据生成的身份验证令牌通过 PowerShell 使用相同的 URI 进行查询时,我收到错误消息 Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.

在获取身份验证令牌方面我是否遗漏了什么? 这是我使用的 GetAuthToken 函数

Function GetAuthToken
{
    param
        (
        [Parameter(Mandatory=$true)]
        $TenantName
        )
    Import-Module Azure
    $clientId = "ef9bcdf0-a675-4cd5-9ec3-fa549f9ee4cf" 
    $redirectUri      = "https://RedirectURI.com" 
    $resourceAppIdURI = "https://graph.microsoft.com"
    $authority = "https://login.microsoftonline.com/$TenantName"
    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
    $Credential = Import-Clixml -Path "C:\MIMA\tom_admin_cred.xml"
    $AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $credential.UserName,$credential.Password
    $authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId,$AADCredential)
    return $authResult
}

这是我用来检索报告的代码

$token = GetAuthToken -TenantName $tenant  
$authHeader = @{
    'Content-Type'='application\json'
    'Authorization'=$token.CreateAuthorizationHeader()
    }
$uri = "https://graph.microsoft.com/beta/auditLogs/directoryAudits?$filter=activityDisplayName eq 'Update user'"
$auditReports = Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get

【问题讨论】:

    标签: powershell microsoft-graph-api office365api


    【解决方案1】:

    问题已解决!该问题是由 Azure AD 应用程序未授予“Auditlog.Read.All”权限引起的。 MSGraph Explorer 中的“修改权限”不知何故不适用于实际的 Azure AD 权限设置(或者它使用的是不同的内置 Azure AD 应用程序?)。

    所以我必须登录到 Azure 门户 -> Azure AD -> 应用注册 -> 设置并在所需权限下添加权限。请注意,更改确实需要一段时间才能生效。我只是等了一夜,第二天早上我就可以在没有 401 错误的情况下检索报告。

    【讨论】:

      【解决方案2】:

      请尝试以下代码:

          $token = GetAuthToken -TenantName $tenant  
          $authHeader = @{
              'Content-Type'='application\json'
              'Authorization'=$token.CreateAuthorizationHeader()
              }
          $uri = "https://graph.microsoft.com/beta/auditLogs/directoryAudits?$filter=activityDisplayName eq 'Update user'"
      
         try{
              $auditReports = Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get
         }
         catch{
              $auditReports = $_.Exception.Response
         }
      

      【讨论】:

      • 我遇到的错误仍然是“未经授权”
      猜你喜欢
      • 2015-07-19
      • 1970-01-01
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 2021-03-27
      • 1970-01-01
      相关资源
      最近更新 更多