Skip to content

Commit 8316d84

Browse files
committed
Merge 'PSMSGraph-Dev/staging' !deploy
Closes #4
2 parents 21c3668 + ae25e42 commit 8316d84

5 files changed

+177
-73
lines changed

PSMSGraph/Public/Get-GraphOauthAccessToken.ps1

+22-18
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
===========================================================================
44
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135
55
Created on: 2/8/2017 10:26 AM
6-
Edited on:: 4/15/2017
6+
Edited on:: 4/22/2017
77
Created by: Mark Kraus
8-
Organization: Mitel
8+
Organization:
99
Filename: Get-GraphOauthAccessToken.ps1
1010
===========================================================================
1111
.DESCRIPTION
@@ -17,7 +17,11 @@
1717
Retieves an OAuth Access Token from Microsoft
1818
1919
.DESCRIPTION
20-
A detailed description of the Get-GraphOauthAccessToken function.
20+
Takes an OAuth Acces Authorization code returned from Get-GraphOauthAuthorizationCode and
21+
requests an OAuth Access Token for the provided resource from Microsoft. A
22+
MSGraphAPI.Oauth.AccessToken object is returned. This object is required for making calls
23+
to Invoke-GraphRequest and many other functions provided by this module.
24+
2125
2226
.PARAMETER AuthenticationCode
2327
The Authentication Code returned from Get-GraphOauthAuthorizationCode
@@ -38,7 +42,8 @@
3842
Azure AD Graph API: https://graph.windows.net
3943
Office 365 Unified Mail API: https://outlook.office.com
4044
41-
If you need to access more than one resrouce, you will need to request multiple OAuth Access Tokens and use the correct tokens for the correct endpoints.
45+
If you need to access more than one resrouce, you will need to request multiple OAuth Access
46+
Tokens and use the correct tokens for the correct endpoints.
4247
4348
.EXAMPLE
4449
PS C:\> $ClientCredential = Get-Credential
@@ -57,12 +62,15 @@
5762
MSGraphAPI.Oauth.AccessToken
5863
5964
.NOTES
65+
See Get-GraphOauthAuthorizationCode for obtaining a OAuth Authorization code.
6066
See Export-GraphOauthAccessToken for exporting Graph Acess Token Objects
6167
See Import-GraphOauthAccessToken for importing exported Graph AcessToken Objects
6268
See Update-GraphOauthAccessToken for refreshing the Graph Access Token
6369
6470
.LINK
6571
http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAccessToken
72+
.LINK
73+
http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAuthorizationCode
6674
.LINK
6775
http://psmsgraph.readthedocs.io/en/latest/functions/Export-GraphOauthAccessToken
6876
.LINK
@@ -131,33 +139,30 @@ function Get-GraphOauthAccessToken {
131139
$Result = Invoke-WebRequest @Params
132140
}
133141
catch {
134-
$response = $_.Exception.Response
135-
$Stream = $response.GetResponseStream()
136-
$Stream.Position = 0
137-
$StreamReader = New-Object System.IO.StreamReader $Stream
138-
$ResponseBody = $StreamReader.ReadToEnd()
139-
$ErrorMessage = "Requesting OAuth Access Token from '{0}' Failed: {1}: {2}" -f $BaseURL,
140-
$_.Exception.Message, $ResponseBody
141-
Write-Error -message $ErrorMessage -Exception $_.Exception
142+
$_.Exception.
143+
psobject.
144+
TypeNames.
145+
Insert(0,'MSGraphAPI.Oauth.Exception')
146+
Write-Error -Exception $_.Exception
142147
return
143148
}
144149
try {
145150
$Content = $Result.Content | ConvertFrom-Json -ErrorAction Stop
146151
}
147152
Catch {
148-
$ErrorMessage = $_.Exception.Message
149153
$Params = @{
150154
MemberType = 'NoteProperty'
151155
Name = 'Respone'
152156
Value = $Result
153157
}
154158
$_.Exception | Add-Member @Params
155-
$Message = "Failed to convert response from JSON: {0}" -f $ErrorMessage
156-
Write-Error -Exception $_.Exception -Message $Message
159+
Write-Error -Exception $_.Exception
157160
return
158161
}
159-
$AccessTokenCredential = [pscredential]::new('access_token', $($Content.access_token | ConvertTo-SecureString -AsPlainText -Force))
160-
$RefreshTokenCredential = [pscredential]::new('refresh_token', $($Content.refresh_token | ConvertTo-SecureString -AsPlainText -Force))
162+
$SecureAccessToken = $Content.access_token | ConvertTo-SecureString -AsPlainText -Force
163+
$SecureRefreshToken = $Content.refresh_token | ConvertTo-SecureString -AsPlainText -Force
164+
$AccessTokenCredential = [pscredential]::new('access_token', $SecureAccessToken )
165+
$RefreshTokenCredential = [pscredential]::new('refresh_token', $SecureRefreshToken)
161166
$Params = @{
162167
Application = $Application
163168
AccessTokenCredential = $AccessTokenCredential
@@ -167,7 +172,6 @@ function Get-GraphOauthAccessToken {
167172
ResponseHeaders = $Result.Headers
168173
LastRequestDate = $RequestedDate
169174
Session = $Session
170-
#ResultObject = $Result
171175
GUID = [guid]::NewGuid()
172176
}
173177
New-GraphOauthAccessToken @Params
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<#
2+
.NOTES
3+
===========================================================================
4+
Created with: VSCode
5+
Created on: 4/21/2017 6:51 PM
6+
Edited on: 4/21/2017
7+
Created by: Mark Kraus
8+
Organization:
9+
Filename: MSGraphAPI.Oauth.Exception.ps1
10+
===========================================================================
11+
.DESCRIPTION
12+
MSGraphAPI.Oauth.Exception Type Definition
13+
#>
14+
15+
@{
16+
Name = 'MSGraphAPI.Oauth.Exception'
17+
Properties = @(
18+
@{
19+
MemberType = 'ScriptProperty'
20+
MemberName = 'JSONResonse'
21+
Value = {
22+
if($this.Response.ContentType -match 'application/json' ){
23+
$Stream= $This.Response.GetResponseStream()
24+
$StreamReader = New-Object System.IO.StreamReader $Stream
25+
$Stream.Position = 0
26+
$StreamReader.ReadToEnd() -replace '\\r\\n',"`r`n" | ConvertFrom-Json
27+
}
28+
}
29+
}
30+
)
31+
}

RELEASE.md

+25-51
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,31 @@
1-
# Version 1.0.24.41 (2017-04-15)
2-
## Module Manifest
3-
* Cleaned up white space at end of file
4-
51
## Functions
6-
### Import-GraphApplication
7-
* Now provides its own error instead of Import-clixml
8-
9-
### Import-GraphOauthAccessToken
10-
* Now provides its own error instead of Import-clixml
11-
12-
### Get-AADGroupMember
13-
* Added ResultsPerPage Paramter to provide access to '$top' query filter.
14-
* Addeed .LINK to Get-AADGroupById
15-
* Addeed .LINK to Get-AADGroupByDisplayName
16-
* Added .INPUTS MSGraphAPI.DirectoryObject.Group
17-
* Added .OUTPUTS MSGraphAPI.DirectoryObject.User
18-
19-
### Get-AADGroupById
20-
* Addeed .LINK to Get-AADGroupByDisplayName
21-
* Addeed .LINK to Get-AADGroupMember
22-
23-
### Get-AADGroupByDisplayName
24-
* Addeed .LINK to Get-AADGroupMember
25-
* Addeed .LINK to Get-AADGroupById
26-
272
### Get-GraphOauthAccessToken
28-
* **Breaking Change**: Removed ```ResultVariable``` and related debugging code that should never have been in production
29-
* Removed ```ResultVariable``` parameter help
30-
* Improved error reporting
31-
* Fixed ```Resource``` parameter documentation
32-
* Imrpoved Example
33-
* Removed dangling ```&``` from ```$Body``` creation
34-
35-
## Build Tools
36-
### psake.ps1
37-
* Block ```staging``` branch recommits so clean pull requests can be made
38-
* Add ```!skiprecommit``` commit tag to block recommits
39-
40-
## Tests
41-
### Get-AADGroupMember.Unit.Tests.ps1
42-
* Created tests for Get-AADGroupMember
3+
* Revised Invoke-WebRequest error handling. Now uses ```MSGraphAPI.Oauth.Exception``` to handle formating
4+
* Simplified error handling for JSON parsing
5+
* Revamped credential object creation for readbility.
6+
* Clean up debug code
437

44-
### Import-GraphApplication.Unit.Tests.ps1
45-
* Created tests for Import-GraphApplication
8+
## Types
9+
### MSGraphAPI.Oauth.Exception
10+
* Added the ```MSGraphAPI.Oauth.Exception``` type to handle OAuth related ```Invoke-Webrequest``` Exceptions
11+
* New ScriptMethod JSONResponse converts the response stream from the ```Invoke-WebRequest``` exception from JSON to PSObject
4612

47-
### Import-GraphOauthAccessToken.Unit.Tests.ps1
48-
* Created tests for Import-GraphOauthAccessToken
49-
50-
### Get-AADGroupById.Unit.Tests.ps1
51-
* Created tests for Get-AADGroupById
13+
## Test
14+
### Get-GraphOauthAccessToken.Unit.Tests.ps1
15+
* Added missing code coverage for ```Invoke-webRequest``` error handling
16+
* Add missing code coverage for JSON parsing error handling
17+
* Now at 100% code coverage for ```Get-GraphOauthAccessToken```!
5218

53-
### Get-AADGroupByDisplayName.Unit.Tests.ps1
54-
* Created tests for Get-AADGroupByDisplayName
19+
## Built Toolds
20+
### psake.ps1
21+
* Adjust recommit logic in PostDeploy task
22+
* Added ```!forcrecommit``` to override default ignores if needed
23+
* Added ```devlop``` to ignored branch for recommits as constant work in the develop branch leads to staging issues.
24+
* Added comment based help file header.
5525

56-
### Get-GraphOauthAccessToken.Unit.Tests.ps1
57-
* Created tests for Get-GraphOauthAccessToken
26+
## Documentation
27+
### Get-GraphOauthAccessToken
28+
* Modifyed Description to something useful
29+
* adjusted formating on ```Resource``` parameter
30+
* Added ```Get-GraphOauthAuthorizationCode``` to Notes
31+
* Added ```Get-GraphOauthAuthorizationCode``` to Links

Tests/Get-GraphOauthAccessToken.Unit.Tests.ps1

+76-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
===========================================================================
44
Created with: VSCode
55
Created on: 4/13/2017 04:25 AM
6-
Edited on:
6+
Edited on: 4/22/2017
77
Created by: Mark Kraus
88
Organization:
99
Filename: Get-GraphOauthAccessToken.Unit.Tests.ps1
@@ -47,6 +47,28 @@ $AuthCode = [pscustomobject]@{
4747
AuthCodeBaseURL = 'https://login.microsoftonline.com/common/oauth2/authorize'
4848
Issued = Get-date
4949
}
50+
$BadAuthCodeSecret = '09876'
51+
$SecBadAuthCodeSecret = $BadAuthCodeSecret | ConvertTo-SecureString -AsPlainText -Force
52+
$BadAuthCodeCredential = [system.Management.Automation.PSCredential]::new('AuthCode', $SecBadAuthCodeSecret)
53+
$BadAuthCode = [pscustomobject]@{
54+
PSTypeName = 'MSGraphAPI.Oauth.AuthorizationCode'
55+
AuthCodeCredential = $BadAuthCodeCredential
56+
ResultURL = 'https://loclahost2'
57+
Application = $App
58+
AuthCodeBaseURL = 'https://login.microsoftonline.com/common/oauth2/authorize'
59+
Issued = Get-date
60+
}
61+
$BadJSONAuthCodeSecret = '54321'
62+
$SecBadJSONAuthCodeSecret = $BadJSONAuthCodeSecret | ConvertTo-SecureString -AsPlainText -Force
63+
$BadJSONAuthCodeCredential = [system.Management.Automation.PSCredential]::new('AuthCode', $SecBadJSONAuthCodeSecret)
64+
$BadJSONAuthCode = [pscustomobject]@{
65+
PSTypeName = 'MSGraphAPI.Oauth.AuthorizationCode'
66+
AuthCodeCredential = $BadJSONAuthCodeCredential
67+
ResultURL = 'https://loclahost2'
68+
Application = $App
69+
AuthCodeBaseURL = 'https://login.microsoftonline.com/common/oauth2/authorize'
70+
Issued = Get-date
71+
}
5072

5173
$Params = @{
5274
AuthenticationCode = $AuthCode
@@ -63,8 +85,26 @@ $VerifyBody = @(
6385
'&resource=https%3a%2f%2fgraph.microsoft.com'
6486
'&client_secret=54321'
6587
) -Join ''
88+
$VerifyBadBody = @(
89+
'grant_type=authorization_code'
90+
'&redirect_uri=https%3a%2f%2flocalhost'
91+
'&client_id=12345'
92+
'&code=09876'
93+
'&resource=https%3a%2f%2fgraph.microsoft.com'
94+
'&client_secret=54321'
95+
) -Join ''
96+
$VerifyBadJSONBody = @(
97+
'grant_type=authorization_code'
98+
'&redirect_uri=https%3a%2f%2flocalhost'
99+
'&client_id=12345'
100+
'&code=54321'
101+
'&resource=https%3a%2f%2fgraph.microsoft.com'
102+
'&client_secret=54321'
103+
) -Join ''
66104
$ValidBodies = @(
67105
$VerifyBody
106+
$VerifyBadBody
107+
$VerifyBadJSONBody
68108
)
69109

70110
$JWT = @(
@@ -142,6 +182,25 @@ Describe $Command -Tags Unit {
142182
}
143183
return $MockResponse
144184
}
185+
Mock -CommandName Invoke-WebRequest -ModuleName PSMSGraph -ParameterFilter {$Body -eq $ValidBodies[1]} -MockWith {
186+
$Params = {
187+
Uri = $Uri
188+
Method = $Method
189+
ErrorAction = 'Stop'
190+
Body = $bode
191+
ContentType = $ContentType
192+
Session = $Session
193+
UseBasicParsing = $true
194+
}
195+
Microsoft.PowerShell.Utility\Invoke-WebRequest @Params
196+
}
197+
Mock -CommandName Invoke-WebRequest -ModuleName PSMSGraph -ParameterFilter {$Body -eq $ValidBodies[2]} -MockWith {
198+
$MockResponse = [pscustomobject]@{
199+
Content = 'This is bad JSON'
200+
Headers = $Global:ResponseHeaders
201+
}
202+
return $MockResponse
203+
}
145204
It 'Does not have errors when passed required parameters' {
146205
$LocalParams = $Params.psobject.Copy()
147206
{ & $Command @LocalParams -ErrorAction Stop } | Should not throw
@@ -161,7 +220,22 @@ Describe $Command -Tags Unit {
161220
$Object = & $Command @LocalParams | Select-Object -First 1
162221
$Object.psobject.typenames.where({ $_ -eq $TypeName }) | Should be $TypeName
163222
}
223+
It "Throws a MSGraphAPI.Oauth.Exception exception on Invoke-WebRequest erros." {
224+
$LocalParams = $Params.psobject.Copy()
225+
$LocalParams.AuthenticationCode = $BadAuthCode
226+
Try{
227+
& $Command @LocalParams -ErrorAction Stop
228+
}
229+
Catch{
230+
$Exception = $_
231+
}
232+
$Exception.Exception.psobject.typenames -contains 'MSGraphAPI.Oauth.Exception' | should be $true
233+
}
234+
It "Throws an exception on JSON parse erros." {
235+
$LocalParams = $Params.psobject.Copy()
236+
$LocalParams.AuthenticationCode = $BadJSONAuthCode
237+
{ & $Command @LocalParams -ErrorAction Stop } | should throw 'Invalid JSON'
238+
}
164239
}
165-
166240
Remove-Variable -Scope Global -Name ResponseHeaders
167241
Remove-Variable -Scope Global -Name JSONResponse

psake.ps1

+23-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,17 @@
1+
<#
2+
.NOTES
3+
===========================================================================
4+
Created with: Unknown
5+
Created on: Unknown
6+
Edited on:: 4/22/2017
7+
Created by: Unknown
8+
Organization:
9+
Filename: psake.ps1
10+
oriringal: https://github.com/KevinMarquette/PSGraph/blob/master/psake.ps1
11+
===========================================================================
12+
.DESCRIPTION
13+
psake Build Automation
14+
#>
115
# PSake makes variables declared here available in other scriptblocks
216
# Init some things
317
Properties {
@@ -283,8 +297,15 @@ Task PostDeploy -depends Deploy {
283297
cmd /c "git status 2>&1"
284298
# Do not recommit to staging so that clean pull request can be perfomred
285299
if (
286-
$ENV:BHBranchName -notlike "staging" -or
287-
$ENV:BHCommitMessage -match '!skiprecommit'
300+
$ENV:BHCommitMessage -notmatch '!skiprecommit' -and
301+
(
302+
$ENV:BHCommitMessage -match '!forcerecommit' -or
303+
(
304+
$ENV:BHBranchName -notlike "staging" -and
305+
$ENV:BHBranchName -notlike "develop"
306+
307+
)
308+
)
288309
){
289310
"git push origin $ENV:BHBranchName"
290311
cmd /c "git push origin $ENV:BHBranchName 2>&1"

0 commit comments

Comments
 (0)