-
Notifications
You must be signed in to change notification settings - Fork 17
/
ms-graph-api-rest.ps1
226 lines (193 loc) · 8.12 KB
/
ms-graph-api-rest.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
<#
.SYNOPSIS
microsoft graph rest api script
.DESCRIPTION
microsoft graph rest api script
24-07-08 08:19:44 may need to create a new app registration in azure portal as default one has been modified
for ms internal connect must be made from ms device
.NOTES
https://myapps.microsoft.com/ <--- can only be accessed from 'work' account
have to set 'api permissions' on app registration. add 'microsoft graph' 'application permissions'
https://docs.microsoft.com/en-us/graph/auth-v2-user
https://login.microsoftonline.com/common/adminconsent?client_id={client-id}
https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow
https://docs.microsoft.com/en-us/azure/active-directory/develop/sample-v2-code
https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc
schema:
https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration
.LINK
[net.servicePointManager]::Expect100Continue = $true;[net.servicePointManager]::SecurityProtocol = [net.SecurityProtocolType]::Tls12;
invoke-webRequest "https://raw.githubusercontent.com/jagilber/powershellScripts/master/ms-graph-api-rest.ps1" -outFile "$pwd\ms-graph-api-rest.ps1";
.\ms-graph-api-rest.ps1
#>
[cmdletbinding()]
param(
$tenantId = 'common',
[ValidateSet('v1.0', 'beta')]
$apiVersion = 'beta', #'v1.0'
$graphApiUrl = "https://graph.microsoft.com/$apiVersion/$tenantId/",
$query = 'applications', #'users', # 'servicePrincipals',
$clientId = '14d82eec-204b-4c2f-b7e8-296a70dab67e', # well-known ps graph client id generated on connect
$clientSecret,
[ValidateSet("get", "post")]
$method = "get",
$body = @{},
$accessToken = $global:accessToken,
$headers = @{
'authorization' = "Bearer $accessToken"
'accept' = 'application/json'
'consistencylevel' = 'eventual'
'content-type' = 'application/json'
},
$scope = 'user.read openid profile Application.ReadWrite.All User.ReadWrite.All Directory.ReadWrite.All Domain.Read.All', # 'https://graph.microsoft.com/.default', #'Application.Read.All offline_access user.read mail.read',
[ValidateSet('urn:ietf:params:oauth:grant-type:device_code', 'client_credentials', 'authorization_code')]
$grantType = 'urn:ietf:params:oauth:grant-type:device_code', #'client_credentials', #'authorization_code'
#$redirectUrl = 'http://localhost',
[switch]$force
)
$global:logonResult = $null
function main() {
if (!$clientId -and !$clientSecret) {
write-error '$clientid and $clientSecret need to be specified'
return
}
if (!$global:accessToken -or ($global:accessTokenExpiration -lt (get-date)) -or $force) {
get-restToken -tenantId $tenantId -grantType $grantType -clientId $clientId -clientSecret $clientSecret -scope $scope
}
$results = call-graphQuery
$global:restResultsJson = $results | convertto-json -depth 5
write-host "use: `$global:restResults" -ForegroundColor Cyan
write-host "use: `$global:restResultsJson" -ForegroundColor Cyan
return $results
}
function get-restAuth($tenantId, $clientId, $scope, $uri) {
# requires app registration api permissions with 'devops' added
# so cannot use internally
write-host "auth request" -ForegroundColor Green
$error.clear()
$uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/devicecode"
$Body = @{
'client_id' = $clientId
'scope' = $scope
}
$params = @{
ContentType = 'application/x-www-form-urlencoded'
Body = $Body
Method = 'post'
URI = $uri
}
Write-Verbose ($params | convertto-json)
$error.Clear()
write-host "invoke-restMethod $uri" -ForegroundColor Cyan
$global:authresult = Invoke-RestMethod @params -Verbose -Debug
write-host "auth result: $($global:authresult | convertto-json)"
write-host "rest auth finished"
return $global:authresult
}
function get-restToken($tenantId, $grantType, $clientId, $clientSecret, $scope) {
# requires app registration api permissions with 'devops' added
# will retry on device code until complete
write-host "token request" -ForegroundColor Green
$global:logonResult = $null
$error.clear()
$uri = "https://login.windows.net/$tenantId/oauth2/v2.0/token"
$headers = @{
'content-type' = 'application/x-www-form-urlencoded'
'accept' = 'application/json'
}
if ($grantType -ieq 'urn:ietf:params:oauth:grant-type:device_code') {
$global:authResult = get-restAuth -tenantId $tenantId -clientId $clientId -scope $scope
$Body = @{
'client_id' = $clientId
'device_code' = $global:authresult.device_code
'grant_type' = $grantType
}
}
elseif ($grantType -ieq 'client_credentials') {
$Body = @{
'client_id' = $clientId
'client_secret' = $clientSecret
'grant_type' = $grantType
}
}
elseif ($grantType -ieq 'authorization_code') {
$global:authResult = get-restAuth
$Body = @{
'client_id' = $clientId
'code' = $global:authresult.code
'grant_type' = $grantType
}
}
$params = @{
Headers = $headers
Body = $Body
Method = 'Post'
URI = $uri
}
write-verbose ($params | convertto-json)
write-host "invoke-restMethod $uri" -ForegroundColor Cyan
$endTime = (get-date).AddSeconds($global:authresult.expires_in)
while ($endTime -gt (get-date)) {
write-verbose "logon timeout: $endTime current time: $(get-date)"
$error.Clear()
try {
$global:logonResult = Invoke-RestMethod @params -Verbose -Debug
write-host "logon result: $($global:logonResult | convertto-json)"
$global:accessToken = $global:logonResult.access_token
$global:accessTokenExpiration = ((get-date).AddSeconds($global:logonResult.expires_in))
return ($global:accessToken -ne $null)
}
catch [System.Exception] {
$errorMessage = ($_ | convertfrom-json)
if ($errorMessage -and ($errorMessage.error -ieq 'authorization_pending')) {
write-host "waiting for device token result..." -ForegroundColor Yellow
write-host "$($global:authresult.message)" -ForegroundColor Green
start-sleep -seconds $global:authresult.interval
}
else {
write-host "exception: $($error | out-string)`r`n this: $($_)`r`n"
write-host "logon error: $($errorMessage | convertto-json)"
write-host "breaking"
break
}
}
}
write-host "rest logon returning"
return $global:accessToken
}
function call-graphQuery () {
write-host "executing graph query" -ForegroundColor Green
$adoAuthHeader = $headers.Clone()
$adoAuthHeader.authorization = "Bearer $global:accessToken"
$uri = $graphApiUrl + $query
$global:restResults = [collections.ArrayList]::new()
while ($true) {
$parameters = @{
Uri = $uri
Method = $method
Headers = $adoAuthHeader
Erroraction = 'continue'
Body = $body
}
Write-Verbose "graph connection parameters: $($parameters | convertto-json)"
write-host "invoke-restMethod $uri" -ForegroundColor Cyan
$error.clear()
$global:restQuery = invoke-restMethod @parameters
[void]$global:restResults.Add($global:restQuery.value)
write-host "rest result: $($global:restQuery| convertto-json)"
if ($error) {
write-error "exception: $($error | out-string)"
return $null
}
if (!($restQuery.'@odata.nextLink')) {
write-verbose "no next link"
break
}
else {
$uri = $restQuery.'@odata.nextLink'
}
}
return $global:restResults
}
main