使用 PowerShell 模拟 Postman 请求失败

Mimic a Postman request with PowerShell fails

我正在尝试通过 Graph API 为特定 SharePoint 站点设置权限。在 postman 中,我执行以下操作:

这行得通。但是,当我尝试在 PowerShell 中执行相同操作时,我收到了错误的请求:

cls

# https://docs.microsoft.com/en-us/graph/api/site-get-permission?view=graph-rest-1.0&tabs=http

$secret = "xxx.5i2v"
$clientid="xx-45f3-464f-xx-xx"
$tenantid="xx-x-4f1f-xx-x"


$Body = @{
    'tenant' = $tenantid
    'client_id' = $clientid
    'scope' = 'https://graph.microsoft.com/.default'
    'client_secret' = $secret
    'grant_type' = 'client_credentials'
}

$Params = @{
    'Uri' = "https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token"
    'Method' = 'Post'
    'Body' = $Body
    'ContentType' = 'application/x-www-form-urlencoded'
}

$AuthResponse = Invoke-RestMethod @Params

$Headers = @{
    'Authorization' = "Bearer $($AuthResponse.access_token)"    
    'ContentType' = 'application/json'
}

# WORKS!
$Result = Invoke-RestMethod -Uri 'https://graph.microsoft.com/v1.0/sites/xx-53D2-xx-xx-xx/permissions' -Headers $Headers
$bodyTxt = $Result | ConvertTo-Json -Depth 100
write-host $bodyTxt 


$body = @{
    roles               = @("write")    
    grantedToIdentities = @( @{
            application = @{
                displayName = "Test 7"                
                id = "xx-45f3-xx-aac4-xx"                
            }
        })
}

$bodyTxt = $body | ConvertTo-Json -Depth 100

# FAILS
Invoke-WebRequest -Uri 'https://graph.microsoft.com/v1.0/sites/xx-53D2-xx-xx-xx/permissions' -Method POST -Body $body -Headers $Headers

这一定是我创建 post 请求的方式。任何指向我做错了什么的指针?

您需要为 Invoke-WebRequest commandlet 指定正文的内容类型。

Invoke-WebRequest 
     -Uri 'https://graph.microsoft.com/v1.0/sitessite-id/permissions' 
     -Method POST 
     -Body  ($body  | ConvertTo-Json -Depth 10) 
     -ContentType "application/json"
     -Headers $Headers

您可能还对 MS Graph 感兴趣PowerShell SDK which does this in few steps which will only require setting up certificate based access

Connect-MgGraph -ClientID $YOUR_APP_ID -TenantId $YOUR_TENANT_ID -CertificateThumbprint $YOUR_CERT_SUBJECT

$body = @{
   roles               = @("write")    
     grantedToIdentities = @( @{
        application = @{
            displayName = "Graph Client App"                
            id = "your-app-id"                
          }
      })
 }


 New-MgSitePermission -SiteId "site-id" -BodyParameter $body