Invoke-RestMethod : The remote server returned an error: (403) Forbidden PowerShell - powershell

I want to get the display name and createdDateTime of Azure AD Groups by calling MS Graph from PowerShell.
For that, I'm using below PS Script:
$Body = #{
client_id = "app_id"
client_secret = "secret"
scope = "https://graph.microsoft.com/.default"
grant_type = 'client_credentials'
}
$Connect_Graph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/my_tenant_id/oauth2/v2.0/token" -Method Post -Body $Body
$token = $Connect_Graph.access_token
$query = "https://graph.microsoft.com/v1.0/groups/"
$groups = (Invoke-RestMethod -Headers #{Authorization = "Bearer $($token)"} -Uri $query -Method Get).value | Select displayName, createdDateTime
It failed with 403 Forbidden
Invoke-RestMethod : The remote server returned an error: (403) Forbidden.
At C:\Users\script.ps1:13 char:12
+ $groups = (Invoke-RestMethod -Headers #{Authorization = "Bearer $($to ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I have given permissions for Group.Read.All and Directory.Read.All.

Please check what type of permissions you granted for Group.Read.All and Directory.Read.All.
If you are trying to access the API as signed-in user, then you have to use Delegated permissions.
If you are trying to access the API without signed-in user, then you have to use Application permissions.
I executed the same script in my environment and got the same error when I have Delegated permissions without signed-in user like below:
To resolve the error, I granted Application permissions for Group.Read.All and Directory.Read.All and executed the below script:
$Body = #{
client_id = "app_id"
client_secret = "secret"
scope = "https://graph.microsoft.com/.default"
grant_type = 'client_credentials'
}
$Connect_Graph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/my_tenant_id/oauth2/v2.0/token" -Method Post -Body $Body
$token = $Connect_Graph.access_token
$query = "https://graph.microsoft.com/v1.0/groups/"
(Invoke-RestMethod -Headers #{Authorization = "Bearer $($token)"} -Uri $query -Method Get).value | Select displayName, createdDateTime
And I got the results successfully like below:

Related

How to assign users office365 licenses using groups with Microsoft graph and PowerShell

I'm working on a PowerShell script to assign users office 365 license based on group (security group). So, i have created app registration and assigned the required API permissions.
When I try to run my script, i get the error below
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At line:1 char:1
+ Invoke-RestMethod -Uri $uri -Body $body -ContentType "application/jso ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Below is the entire script
$connectiondetails = #{
# This ids and secret are present in the overview and certificate & secret page of our application in azure AD
# Tenant ID here
'tenantid' = ""
# Application (client) ID here
'clientid' = ""
# Secret id here
'ClientSecret' = "" | ConvertTo-SecureString -AsPlainText -Force
}
$token = Get-MsalToken #connectiondetails
$tokenid_ = $token.AccessToken
# $uri = "https://graph.microsoft.com/v1.0/groups"
# $grp = Invoke-RestMethod -Uri $uri -Headers #{Authorization=("bearer {0}" -f $tokenid_)}
# $grp
$uri = "https://graph.microsoft.com/v1.0/groups/ffbabc6f-aa87-40f3-8665-9d140e4a7adb/assignLicense"
$body = "{""SkuId"":""cbdc14ab-d96c-4c30-b9f4-6ada7cdc1d46""}"
# assign license call
Invoke-RestMethod -Uri $uri -Body $body -ContentType "application/json" -Method post -Headers #{Authorization=("bearer {0}" -f $tokenid_)}
Permissions assigned to the app
I need assistance to know what am doing wrong. Thank you.
Solutions tried
The body for the request to add license requires addLicenses property with permissions Group.ReadWrite.All and Directory.ReadWrite.All.
{
"addLicenses": [
{
"skuId": "cbdc14ab-d96c-4c30-b9f4-6ada7cdc1d46"
}
],
"removeLicenses": []
}
PS
$uri = "https://graph.microsoft.com/v1.0/groups/ffbabc6f-aa87-40f3-8665-9d140e4a7adb/assignLicense"
# create json object
$data = #{
"addLicenses" = #(
#{
"skuId" = "cbdc14ab-d96c-4c30-b9f4-6ada7cdc1d46"
}
)
"removeLicenses" = #()
}
# convert to JSON-formatted string
$body = $data | ConvertTo-Json
# assign license call
Invoke-RestMethod -Uri $uri -Body $body -ContentType "application/json" -Method post -Headers #{Authorization=("bearer {0}" -f $tokenid_)}
Resources:
Group - assign licenses
This article seems to explain the script building in detail
Create MS Graph scripts with AAD App

Using Microsoft Graph API in PowerShell to Get Planner Tasks

I am trying to use the Microsoft Graph API with Application registration and permissions to modify Planner Tasks.
I have successfully registered my application and set permissions to (Directory.Read.All, Directory.ReadWrite.All, Group.Read.All, Group.ReadWrite.All, GroupMember.Read.All, GroupMember.ReadWrite.All, User.Read). but I can't pull the Plans for any group I always get the error:
> Invoke-RestMethod : { "error": {
> "code": "UnknownError",
> "message": "UserDeleted",
> "innerError": {
> "request-id": "043b140e-aa18-42aa-8672-7c164277553f",
> "date": "2020-05-16T22:47:10"
> } } } At C:\Users\jlamb\Scripts\Connect-MicrosoftGraph.ps1:36 char:17
> + ... $Response = Invoke-RestMethod -Method Get -Headers $headers -Uri $uri ...
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod],
> WebException
> + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I don't understand what this error means.
Here is my sample code:
$tenant = '67a80b53-1b4f-4278-b269-xxxxxxxxxxxx' #Directory ID
$client_id = 'da398f63-3b2b-4dc3-b594-54cbc0a2924f' #Application ID
$scope = 'https://graph.microsoft.com/.default'
$client_secret = 'xxxxx-xxxx.xxxxxxx.xxxxxxxxxxx.xxx' #PowerShellPOC, expires 5/16/2021
$grant_type = 'client_credentials'
if (-not $headers) {
$body = #{client_id=$client_id; scope=$scope; client_secret=$client_secret; grant_type=$grant_type}
$uri = "https://login.microsoftonline.com/$tenant/oauth2/v2.0/token"
$Response = Invoke-RestMethod -Method Post -Uri $uri -Body $body
$access_token = $Response.access_token
$headers = #{
Authorization = "$($Response.token_type) $($Response.access_token)"
ExpiresOn = $($Response.expires_in)
}
}
Write-Host "Getting Groups"
$uri = "https://graph.microsoft.com/v1.0/groups?$orderby=displayName"
$Response = $null
$Response = Invoke-RestMethod -Method Get -Headers $headers -Uri $uri
$Response.value |ft id, displayName
#this works and returns 100 groups
foreach ($groupId in $($Response.value.id)) {
$groupId
$uri = "https://graph.microsoft.com/v1.0/groups/$groupId/planner/plans"
$Response = $null
$Response = Invoke-RestMethod -Method Get -Headers $headers -Uri $uri
$Response.value |ft
}
I've also tried pulling tasks from a plan I know exists:
$plan_id = 'zBgxnzXTNEaGeW9Hz1CVSmQAHpg2'
$uri = "https://graph.microsoft.com/v1.0/planner/plans/$plan_id/tasks"
$uri
$Response = $null
$Response = Invoke-RestMethod -Method Get -Headers $headers -Uri $uri
$Response.value |ft
I get the same error.
I see you are using an app secret, and therefore you are using application permissions that are not supported. Need to be delegated.
Take a look at the Docs pages for the requests, and there you see if app or delegated is supported.
Here you have two ways of getting a token for delegated access:
https://gist.githubusercontent.com/leeford/04fc4c2d4404c2a31a172923d9bed8ee/raw/294f2303b306b4bf7a31f1541ff4d59dc5b40ca2/AzureADGraphAPIUserToken.ps1
https://www.lee-ford.co.uk/graph-api-device-code/

Issue to get/create message in channel

I'm trying to use graph api with powershell (/teams/{id}/channels/{id}/messages)
For this i have an azure app with api permissions (delegated and application) "Group.ReadWrite.All and some others. My account is as administrator
I received my token correctly with this
$Body = #{grant_type = "client_credentials"; resource = "https://graph.microsoft.com"; client_id =
$ClientID; client_secret = $secret; username = $SPLogin; password = $encpassword }
$res = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$TenantId/oauth2/token?api-version=1.0" -Body $bodyStr -Headers $head
$headerUser = #{"Authorization" = "Bearer " + $res.access_token };
Here is what i received as token
token_type : Bearer
expires_in : 3599
ext_expires_in : 3599
expires_on : 1583338248
not_before : 1583334348
resource : https://graph.microsoft.com
access_token : xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
When i have my token correctly i first try to get all messages in channel (https://learn.microsoft.com/en-us/graph/api/channel-list-messages?view=graph-rest-beta&tabs=http)
$apiUrl = "https://graph.microsoft.com/beta/teams/$groupID/channels/$chanelID/messages"
$myPostedMsg = Invoke-RestMethod -Headers $headerUser -Uri $apiUrl -Method Get
Unfortunately it doesn't work as expected and have this error
Invoke-RestMethod : {
"error": {
"code": "UnknownError",
"message": "",
"innerError": {
"request-id": "4cd0e36f-2e0c-4712-b613-bcc350595aee",
"date": "2020-03-04T15:12:53"
}
}
}
At line:1 char:16
+ ... PostedMsg = Invoke-RestMethod -Headers $headerUser -Uri $apiUrl -Met ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-
RestMethod], WebException
+ FullyQualifiedErrorId :
WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I have the same issue if i try to post a message
$body = "{
""body"": {
""content"": ""Ceci est un message"",
""subject"":""Subject"",
""contentType"":""html""
}
}"
$apiUrl = "https://graph.microsoft.com/beta/teams/$groupID/channels/$chanelID/messages"
$myPostedMsg = Invoke-RestMethod -Headers $headerUser -Uri $apiUrl -Body $body -Method Post -ContentType "application/json"
If anyone has already had this issue
Some apis in teams are "protected". You need to request access from microsoft in advance =>
Protected Apis in Microsoft Teams

The remote server returned an error : (401) Unauthorized - PowerShell - Microsoft Graph API

I am trying to get the list of all groups where the resourceProvisioningOptions = Team, here is the url which gets all the data through API call:
$clientID = xxxx
$tenantName = xxxx
$ClientSecret = xxxx
$resource = "https://graph.microsoft.com/"
$ReqTokenBody = #{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
client_Id = $clientID
Client_Secret = $clientSecret
}
$authheader = #{
'Authorization' = "Bearer $($Tokenresponse.access_token)"
'Content-Type'='application\json'
}
$TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody
$test = "'Team'"
$apiUrl = 'https://graph.microsoft.com/beta/groups?$filter=resourceProvisioningOptions/Any(x:x eq {0})' -f $test
$Data = Invoke-RestMethod -Uri $apiUrl -Headers $authheader -Body $ReqTokenBody -Method Get
$Groups = ($Data | select-object Value).Value | Select-Object displayName, id, description, mail | Out-File .\texxtfile.txt
However, I am getting a 401 error when I try to run the script even though I have all the permissions required to make the API call.
You may have picked application permissions in your AAD application. There is an additioanl step. You will need to admin consent your application in the app registration portal to use Group.Read.All to run this. If you have not done this in the UI this will fail.

JIRA Cloud API GET Request - Works in Postman, but not Powershell

I am able to perform a GET Request from Jira successfully in Postman, but am unable to make the same request in Powershell due to an authentication error. I know that my credentials are correct because there are or GET Requests that are successful. My guess is that it has something to do with the URL (https://arnold.jira.com/admin/rest/um/1/user).
Since I know that my credentials are correct, I am not sure what else I can try.
# Create a new session using the Jira REST API
$user = 'john.rambo#arnold.com'
$pass = '8675309'
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = #{
Authorization = $basicAuthValue;
Accept = 'application/json'
}
# Perform the GET Request
$UserEmail = 'dolf.lundgren#arnold.com'
$UserAttributeLink = 'https://arnold.jira.com/admin/rest/um/1/user?email=' + $UserEmail + '&expand=attributes'
$UserAttributes = Invoke-RestMethod ($UserAttributeLink) -Headers $Headers -Method GET -ContentType "application/json"
I expect to have the info returned, but am met with this error:
Invoke-RestMethod : User failed to authenticate
At line:12 char:19
+ ... ttributes = Invoke-RestMethod ($UserAttributeLink) -Headers $Headers ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Method: GET, Reques\u2026PowerShell/6.2.1
}:HttpRequestMessage) [Invoke-RestMethod], HttpResponseException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand