Search code examples
azurepowershellazure-active-directorymicrosoft-graph-api

MS Graph create permssion for Sharepoint Site - POSTMAN OK / Powershell NG


According to MSDoc, I am trying to use powershell to give a site permissoin. I've tried the same on Graph Explorer with a user with Sites.FullControl.All, I got 201 result. Also I am using the same config with POSTMAN, it's also 201 result. enter image description here

However, when I use the following codesnip

# Define parameters
$ClientId = ""
$ClientSecret = ""
$TenantId = ""
$SiteId = ""
$Scope = "https://graph.microsoft.com/.default"
$TokenEndpoint = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
# Create body for the request
$body = @{
    grant_type    = "client_credentials"
    client_id     = $ClientId
    client_secret = $ClientSecret
    scope         = $Scope
}

# Make the POST request
$response = Invoke-RestMethod -Uri $TokenEndpoint -Method POST -Body $body
# Define the URL
$url = "https://graph.microsoft.com/v1.0/sites/$siteId/permissions"

# Define the body content
$body = @{
    roles = @(
        "write"
    )
    grantedToIdentities = @(
        @{
            application = @{
                id = ""
                displayName = ""
            }
        }
    )
}
# Define headers
$headers = @{
    "Content-Type" = "application/json"
    "Authorization" = "Bearer $($response.access_token)"
}

# Send POST request
$response = Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $body

I got the following error

Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At line:41 char:13
+ $response = Invoke-RestMethod -Uri $url -Method Post -Headers $header ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRe  
   quest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Com  
   mands.InvokeRestMethodCommand

We do not have Powershell Graph SDK installed. Want a pure REST api call from powershell. Any suggestions? Thank you

  [1]: https://According%20to%20[Link][1]%20%20%20%20%20[1]:%20https://learn.microsoft.com/en-us/graph/api/site-post-permissions?view=graph-rest-1.0&t

Solution

  • Alternatively, you can directly use Microsoft Graph PowerShell commands to achieve your scenario.

    I registered one application and granted Sites.FullControl.All permission of Application type with admin consent:

    enter image description here

    Now, I ran below PowerShell script by connecting to Microsoft Graph using client secret credentials and got response like this:

    #Install-Module Microsoft.Graph
    
    $ClientId = "appId"
    $TenantId = "tenantId"
    $siteId = "siteId"
    $ClientSecret = "secret"
    $ClientSecretPass = ConvertTo-SecureString -String $ClientSecret -AsPlainText -Force
    $ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ClientId, $ClientSecretPass
    
    Connect-MgGraph -TenantId $TenantId -ClientSecretCredential $ClientSecretCredential
    
    Import-Module Microsoft.Graph.Sites
    
    $params = @{
        roles = @(
            "write"
        )
        grantedToIdentities = @(
            @{
                application = @{
                    id = "appObjId"
                    displayName = "appName"
                }
            }
        )
    }
    
    New-MgSitePermission -SiteId $siteId -BodyParameter $params
    

    Response:

    enter image description here

    When I ran below Graph API call to check the created permissions, I got response like this:

    GET https://graph.microsoft.com/v1.0/sites/siteId/permissions
    

    Response:

    enter image description here

    UPDATE:

    To create permission using REST API calls, you can make use of below modified script where I passed body as Json and got response successfully:

    # Define parameters
    $ClientId = "appId"
    $ClientSecret = "secret"
    $TenantId = "tenantId"
    $SiteId = "siteId"
    $Scope = "https://graph.microsoft.com/.default"
    $TokenEndpoint = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
    
    # Create body for the request
    $body = @{
        grant_type    = "client_credentials"
        client_id     = $ClientId
        client_secret = $ClientSecret
        scope         = $Scope
    }
    
    # Make the POST request to get access token
    $response = Invoke-RestMethod -Uri $TokenEndpoint -Method POST -Body $body
    
    # Define the URL
    $url = "https://graph.microsoft.com/v1.0/sites/$SiteId/permissions"
    
    # Define the body content as JSON string
    $jsonBody = @"
    {
      "roles": ["write"],
      "grantedToIdentities": [{
        "application": {
          "id": "appObjId",
          "displayName": "appName"
        }
      }]
    }
    "@
    
    # Define headers
    $headers = @{
        "Authorization" = "Bearer $($response.access_token)"
        "Content-Type" = "application/json"
    }
    
    # Send POST request
    $response = Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $jsonBody
    
    $response  # This will output the response of the request
    

    Response:

    enter image description here