WhiteboardAdmin.psm1
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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 |
Set-Variable AdalClientId -option Constant -value '1950a258-227b-4e31-a9cf-717495945fc2' Set-Variable AdalRedirectUri -option Constant -value 'https://login.microsoftonline.com/common/oauth2/nativeclient' <# .SYNOPSIS Gets one or more Whiteboards from the Microsoft Whiteboard service and returns them as objects. .PARAMETER UserId The ID of the user account to query Whiteboards for. .PARAMETER WhiteboardId (Optional) The ID of a specific Whiteboard to query, if not specified all whiteboards are queried. .PARAMETER ForceAuthPrompt (Optional) Always prompt for auth. Use to ignore cached credentials. .EXAMPLE Get-Whiteboard -UserId 00000000-0000-0000-0000-000000000001 Get all of a user's Whiteboards. #> function Get-Whiteboard { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [Guid]$UserId, [Parameter(Mandatory=$false)] [Guid]$WhiteboardId, [Parameter(Mandatory=$false)] [switch]$ForceAuthPrompt) $response = Send-GetWhiteboardsRequest ` -UserId $UserId ` -ForceAuthPrompt:$ForceAuthPrompt if ($null -eq $WhiteboardId) { return $response } # Filter client-side since there is no admin GET API that addresses a single whiteboard. return $response | Where-Object {$_.id -eq $WhiteboardId} } function Send-GetWhiteboardsRequest { param( [Parameter(Mandatory=$true)] [Guid]$UserId, [Parameter(Mandatory=$false)] [hashtable]$Headers, [Parameter(Mandatory=$false)] [switch]$ForceAuthPrompt) $response = Invoke-WhiteboardRequest ` -Method GET ` -Endpoint "api/v1.0/users/$UserId/whiteboards" ` -ContentType 'application/json' ` -Headers $Headers ` -ForceAuthPrompt:$ForceAuthPrompt return $response } <# .SYNOPSIS Gets all of the board owners from the Microsoft Whiteboard service in a given geography. The response is a JSON object with the following properties: Items: A list of strings containing the owner ids ContinuationToken: A continuation token to pass in future calls to this API. The token can expire when new results are computed. In this case a 410 is returned, and the call should be retried with a null continuation token. When this situation occurs, duplicate owner ids may be returned. If null, there are no more owners to return. Geography: The geography for which this results were calculated. TenantId: The tenant ID these owners belong to. This data is not live calculated, and instead is based on cached values that are calculated every 2-4 weeks. As a result, admins should be aware that this may be an incomplete list. .PARAMETER Geography The geography to look up whiteboards in. Valid options are "Europe", "Australia", and "Worldwide". "Worldwide" contains all data not stored in Europe or Australia. At the time of writing, this data is stored in the US. .PARAMETER ContinuationToken (Optional) A continuation token based on the last time this function was called. Due to the large volume of boards in a tenant, results are returned in chunks at a time, with a continuation token to signify where to pick up from. To start from the beginning, pass in null. .PARAMETER ForceAuthPrompt (Optional) Always prompt for auth. Use to ignore cached credentials. #> function Get-WhiteboardOwners { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateSet('Worldwide', 'Europe', 'Australia')] [string]$Geography, [Parameter(Mandatory=$false)] [string]$ContinuationToken = $null, [Parameter(Mandatory=$false)] [switch]$ForceAuthPrompt) $response = Send-GetWhiteboardOwnersRequest ` -Geography $Geography ` -ContinuationToken $ContinuationToken ` -ForceAuthPrompt:$ForceAuthPrompt return $response } function Send-GetWhiteboardOwnersRequest { param( [Parameter(Mandatory=$true)] [string]$Geography, [Parameter(Mandatory=$false)] [string]$ContinuationToken = $null, [Parameter(Mandatory=$false)] [hashtable]$Headers, [Parameter(Mandatory=$false)] [switch]$ForceAuthPrompt) if ($Headers -eq $null) { $Headers = @{} } if (!$Headers.ContainsKey("x-ms-continuation")){ $Headers.Add("x-ms-continuation", $ContinuationToken) } if (!$Headers.ContainsKey("x-ms-continuationToken")){ $Headers.Add("x-ms-continuationToken", $ContinuationToken) } $response = Invoke-WhiteboardRequest ` -Method GET ` -Endpoint "api/v1.0/admin/whiteboardowners/geographies/$Geography" ` -ContentType 'application/json' ` -ForceAuthPrompt:$ForceAuthPrompt ` -Headers $Headers return $response } <# .SYNOPSIS Sets the owner for a Whiteboard. .PARAMETER WhiteboardId The Whiteboard for which the owner is being changed. .PARAMETER OldOwnerId The ID of the previous owner. .PARAMETER NewOwnerId The ID of the new owner. .PARAMETER ForceAuthPrompt (Optional) Always prompt for auth. Use to ignore cached credentials. .EXAMPLE Set-WhiteboardOwner -OldOwnerId 00000000-0000-0000-0000-000000000001 -NewOwnerId 00000000-0000-0000-0000-000000000002 Move a Whiteboard from one user to another. #> function Set-WhiteboardOwner { [CmdletBinding( SupportsShouldProcess = $true, ConfirmImpact='High')] param( [Parameter(Mandatory=$true)] [Guid]$WhiteboardId, [Parameter(Mandatory=$true)] [Guid]$OldOwnerId, [Parameter(Mandatory=$true)] [Guid]$NewOwnerId, [Parameter(Mandatory=$false)] [switch]$ForceAuthPrompt) if ($PSCmdlet.ShouldProcess("Whiteboard: $WhiteboardId")) { return Invoke-WhiteboardRequest ` -Method PATCH ` -Endpoint "api/v1.0/users/$OldOwnerId/whiteboards/$WhiteboardId" ` -ContentType 'application/json-patch+json' ` -Body (ConvertTo-Json -Compress @(@{"op"="replace"; "path"="/OwnerId"; "value"=$NewOwnerId })) ` -ForceAuthPrompt:$ForceAuthPrompt } } <# .SYNOPSIS Transfer ownership of all Whiteboards owned by a user to another user. .PARAMETER OldOwnerId The ID of the previous owner. .PARAMETER NewOwnerId The ID of the new owner. .PARAMETER WhatIf Execute the command without making any actual changes. Only calls read methods on the REST service. .PARAMETER ForceAuthPrompt (Optional) Always prompt for auth. Use to ignore cached credentials. .EXAMPLE Invoke-TransferAllWhiteboards -OldOwnerId 00000000-0000-0000-0000-000000000001 -NewOwnerId 00000000-0000-0000-0000-000000000002 -WhatIf Check how many Whiteboards will be transferred without transferring them. .EXAMPLE Invoke-TransferAllWhiteboards -OldOwnerId 00000000-0000-0000-0000-000000000001 -NewOwnerId 00000000-0000-0000-0000-000000000002 Transfer (and prompt before performing any write actions). #> function Invoke-TransferAllWhiteboards { [CmdletBinding( SupportsShouldProcess = $true, ConfirmImpact='High')] param( [Parameter(Mandatory=$true)] [Guid]$OldOwnerId, [Parameter(Mandatory=$true)] [Guid]$NewOwnerId, [Parameter(Mandatory=$false)] [switch]$ForceAuthPrompt) $whiteboards = Get-Whiteboard -UserId $OldOwnerId -ForceAuthPrompt:$ForceAuthPrompt # Only transfer Whiteboards actually owned by this Id $whiteboardsOwned = @($whiteboards | Where-Object { [Guid]::Parse($_.ownerId) -eq $OldOwnerId }) Write-Verbose "Found $($whiteboardsOwned.Length) Whiteboards for owner $($OldOwnerId)" if ($PSCmdlet.ShouldProcess("Whiteboards for Owner: $OldOwnerId")) { $whiteboardsOwned | ForEach-Object { Set-WhiteboardOwner -OldOwnerId $OldOwnerId -NewOwnerId $NewOwnerId -WhiteboardId $_.id -Confirm:$false } } } <# .SYNOPSIS Deletes the specified Whiteboard for the given user from the Microsoft Whiteboard service. If the user is the owner of the whiteboard, the entire whiteboard will be deleted. If the user has joined the whiteboard but does not own it, they will be removed and the whiteboard will still be accessible by others. .PARAMETER UserId The ID of the user account to delete the Whiteboard from. .PARAMETER WhiteboardId The ID of a specific Whiteboard to delete. .PARAMETER ForceAuthPrompt (Optional) Always prompt for auth. Use to ignore cached credentials. .EXAMPLE Remove-Whiteboard -UserId 00000000-0000-0000-0000-000000000001 -WhiteboardId 00000000-0000-0000-0000-000000000002 Deletes the whiteboard #> function Remove-Whiteboard { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [Guid]$UserId, [Parameter(Mandatory=$true)] [Guid]$WhiteboardId, [Parameter(Mandatory=$false)] [switch]$ForceAuthPrompt) if ($PSCmdlet.ShouldProcess("Delete whiteboard $WhiteboardId for User $UserId?")) { Invoke-WhiteboardRequest ` -Method DELETE ` -Endpoint "api/v1.0/users/$UserId/whiteboards/$WhiteboardId" ` -ContentType 'application/json' ` -ForceAuthPrompt:$ForceAuthPrompt } } <# .SYNOPSIS Gets tenant settings from the Microsoft Whiteboard service and returns them as an object. .PARAMETER ForceAuthPrompt (Optional) Always prompt for auth. Use to ignore cached credentials. .EXAMPLE Get-WhiteboardSettings Get the users Whiteboard settings. #> function Get-WhiteboardSettings { [CmdletBinding()] param( [Parameter(Mandatory=$false)] [switch]$ForceAuthPrompt) $response = Invoke-WhiteboardRequest ` -Method GET ` -Endpoint "api/v1.0/whiteboards/enabled" ` -ForceAuthPrompt:$ForceAuthPrompt return $response } <# .SYNOPSIS Sets the tenant settings for the Microsoft Whiteboard services. .PARAMETER Settings The object to use as Whiteboard Settings. Should be retrieved via Get-WhiteboardSettings .PARAMETER ForceAuthPrompt (Optional) Always prompt for auth. Use to ignore cached credentials. .EXAMPLE $settings = Get-WhiteboardSettings $settings.isEnabledGa = $true Set-WhiteboardSettings -Settings $settings Enables Microsoft Whiteboard for your tenant. #> function Set-WhiteboardSettings { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [psobject]$Settings, [Parameter(Mandatory=$false)] [switch]$ForceAuthPrompt) $jsonSettings = ConvertTo-Json $Settings $response = Invoke-WhiteboardRequest ` -Method POST ` -Endpoint "api/v1.0/whiteboards/enabled" ` -ContentType 'application/json' ` -Body $jsonSettings ` -ForceAuthPrompt:$ForceAuthPrompt return $response } <# .SYNOPSIS Gets all the whiteboards associated with a tenant in a specific geography. .PARAMETER Geography The geography to grab the whiteboards from. Valid options are Australia, Europe, or Worldwide. .PARAMETER IncrementalRunName (Optional) Saves incremental progess as the cmdlet runs. Use to resume a partially completed Get-WhiteboardsForTenant. Use the same IncrementalRunName on later calls to continue a previously cancelled/failed run Writes progress and results to txt files in the current directory: "Whiteboards-*.txt" contains the incremental results containing whiteboards in JSON for the tenant where * is the provided IncrementalRunName "WhiteboardAdminRun-*.txt" contains the state of the current where * is the provided IncrementalRunName. This file should not be modified manually .PARAMETER ForceAuthPrompt (Optional) Always prompt for auth. Use to ignore cached credentials. .EXAMPLE Get-WhiteboardsForTenant -Geography Europe Gets all the whiteboards associated with the caller's tenant in Europe .EXAMPLE Get-WhiteboardsForTenant -Geography Europe -IncrementalRunName 1 Gets all the tenant whiteboards in Europe and incrementally writes them to Whiteboards-1.txt file in the current directory. Saves progress at WhiteboardAdminRun-1.txt file until the request is completed. If this file already exists, continues the progress using the last saved token. #> function Get-WhiteboardsForTenant { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateSet('Worldwide', 'Europe', 'Australia')] [string]$Geography, [Parameter(Mandatory=$false)] [string]$IncrementalRunName, [Parameter(Mandatory=$false)] [switch]$ForceAuthPrompt) # helper function for calling the Get-WhiteboardOwners API wrapped in a retry function Get-WhiteboardOwnersWithRetry( [Parameter(Mandatory=$true)] [string]$Geography, [Parameter(Mandatory=$false)] [string]$ContinuationToken, [Parameter(Mandatory=$true)] [object]$AuthenticationToken) { $Headers = @{ "Authorization" = Get-WhiteboardAuthenticationHeader -AuthenticationToken $AuthenticationToken } $retryCount = 0 while ($true) { try { $results = Send-GetWhiteboardOwnersRequest ` -Geography $Geography ` -ContinuationToken $ContinuationToken ` -Headers $Headers return $results } catch { Write-Verbose "Failed to get owners. Retry count: $retryCount" $retryCount++ if ($retryCount -gt 4) { throw $_.Exception } } } } # helper function for calling the Get-Whiteboard API for a user wrapped in a retry and filtering for # a specific geography. function Get-WhiteboardsInGeographyForUser( [Parameter(Mandatory=$true)] [string]$OwnerId, [Parameter(Mandatory=$true)] [string]$Geography, [Parameter(Mandatory=$true)] [object]$AuthenticationToken) { $retryCount = 0 $baseApi = "" if ($Geography -eq 'Worldwide') { $baseApi = "us*" } elseif ($Geography -eq 'Europe') { $baseApi = "eu*" } elseif ($geography -eq 'Australia') { $baseApi = "au*" } $Headers = @{ "Authorization" = Get-WhiteboardAuthenticationHeader -AuthenticationToken $AuthenticationToken } while ($true) { try { return Send-GetWhiteboardsRequest -UserId $ownerId -Headers $Headers | Where-Object -Property baseApi -like $baseApi } catch { Write-Verbose "Failed to get whiteboards for $ownerId. Retry count: $retryCount" $retryCount++ if ($retryCount -gt 4) { throw $_.Exception } } } } # A helper function to set up files for incremental results between runs. Allows for continuing from a previously cancelled run function Set-WhiteboardsIncrementalRun( [Parameter(Mandatory=$true)] [string]$ContinuationTokenFileName, [Parameter(Mandatory=$true)] [string]$WhiteboardResultsFileName) { if(Test-Path -Path $ContinuationTokenFileName) { $existingContinuationToken = Get-Content -Path $ContinuationTokenFileName if(-not [string]::IsNullOrEmpty($existingContinuationToken)) { Write-Host "Previous run detected. Continuing get-whiteboard enumeration`n" return $existingContinuationToken } else { Write-Warning "$ContinuationTokenFileName is corrupted. Whiteboard enumeration will start from the beginning.`n" } } New-Item -Name $WhiteboardResultsFileName -ItemType "file" -Force | Out-Null Write-Host "Starting new get-whiteboard enumeration and clearing any previous run data`n" Write-Host "Whiteboards will be added to $WhiteboardResultsFileName in the current directory`n" Write-Host "The run state will be written to $ContinuationTokenFileName. This file does not contain readable data, but necessary for incremental results. To resume a previous cmdlet call, make the same call with the same parameters`n" return $null } $continuationToken = $null # Set up files to write the results for incremental runs. Allows for continuing from a previously cancelled run $incrementalResults = -not [string]::IsNullOrEmpty($IncrementalRunName) $continuationTokenFileName = "WhiteboardAdminRun-$IncrementalRunName.txt" $whiteboardResultsFileName = "Whiteboards-$IncrementalRunName.txt" if($incrementalResults) { $continuationToken = Set-WhiteboardsIncrementalRun -ContinuationTokenFileName $continuationTokenFileName -WhiteboardResultsFileName $whiteboardResultsFileName } $whiteboardsAll = @() $AuthenticationToken = Get-WhiteboardAuthenticationToken -ForceAuthPrompt:$ForceAuthPrompt do { Write-Verbose "Getting page of owners`n" $AuthenticationToken = Update-WhiteboardAuthenticationToken -AuthenticationToken $AuthenticationToken $results = Get-WhiteboardOwnersWithRetry -Geography $Geography -ContinuationToken $continuationToken -AuthenticationToken $AuthenticationToken $count = $results.items.Count Write-Verbose "Found $count whiteboard owners in $Geography" $continuationToken = $results.continuationToken if(-not [string]::IsNullOrEmpty($continuationToken)){ Write-Verbose "More whiteboard owners exist" } foreach($ownerId in $results.items) { Write-Verbose "Adding boards for owner $ownerId`n" $AuthenticationToken = Update-WhiteboardAuthenticationToken -AuthenticationToken $AuthenticationToken $whiteboards = Get-WhiteboardsInGeographyForUser -OwnerId $ownerId -Geography $Geography -AuthenticationToken $AuthenticationToken $wbCount = $whiteboards.Count Write-Verbose "User $ownerId has $wbCount whiteboards in $Geography" if($incrementalResults) { foreach($whiteboard in $whiteboards) { Add-Content -Path $whiteboardResultsFileName -Value (ConvertTo-Json $whiteboard -Compress -Depth 1) Write-Verbose "$ownerId's whiteboards appended to file $whiteboardResultsFileName" } } else { $whiteboardsAll = $whiteboardsAll + $whiteboards } } # Store the continuation token if($incrementalResults) { $continuationToken | Out-File $continuationTokenFileName Write-Verbose "Wrote continuation token to file $continuationTokenFileName" } } while(-not [string]::IsNullOrEmpty($continuationToken)) if($incrementalResults) { Remove-Item $continuationTokenFileName Write-Verbose "Removed continuation token file $continuationTokenFileName" Write-Host "Completed Get-WhiteboardsForTenant. Results stored in $whiteboardResultsFileName" return } else { return $whiteboardsAll } } function Invoke-WhiteboardRequest( [Parameter(Mandatory=$true)] [Microsoft.PowerShell.Commands.WebRequestMethod]$Method, [Parameter(Mandatory=$true)] [string]$Endpoint, [Parameter(Mandatory=$false)] [string]$ContentType = $null, [Parameter(Mandatory=$false)] [string]$Body = $null, [Parameter(Mandatory=$false)] [hashtable]$Headers = $null, [Parameter(Mandatory=$false)] [switch]$ForceAuthPrompt) { # Make sure TLS 1.2 is a supported protocol since this is all the whiteboard service supports. [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol, [Net.SecurityProtocolType]::Tls12 if (!$Headers.Count){ $Headers = @{} } if(!$Headers.ContainsKey('Authorization')) { $Headers['Authorization'] = Get-WhiteboardAuthenticationHeader -ForceAuthPrompt:$ForceAuthPrompt } $invokeRestMethodArgs = @{ Method = $Method Uri = "https://$(Get-WhiteboardHostName -Environment $env:Environment)/$Endpoint" ContentType = $ContentType UserAgent = "WhiteboardAdminModule/$((Get-Module WhiteboardAdmin | Select-Object -First 1).Version)" Headers = $Headers } if (-Not [string]::IsNullOrEmpty($Body)) { $invokeRestMethodArgs["Body"] = $Body } try { return Invoke-RestMethod @invokeRestMethodArgs } catch [System.Net.WebException] { $ex = $_.Exception if ($ex.Status -ne [System.Net.WebExceptionStatus]::ProtocolError) { # Rethrow the exception if the failure wasn't caused by a protocol error. throw $ex } $response = $ex.Response if ($response.StatusCode -ne [System.Net.HttpStatusCode]::Unauthorized) { # Rethrow the exception if the failure wasn't caused by a unauthorized response throw $ex } # Try to deserialize the adal claims challenge. # This can happen if the endpoint makes an onbehalf # of request that requires additional claims (like MFA) try { $authenticateHeader = $response.Headers["WWW-Authenticate"] $claims = Get-ClaimsFromWWWAuthenticateHeader($authenticateHeader) if ([string]::IsNullOrEmpty($claims)) { throw $ex } } catch { throw $ex } $invokeRestMethodArgs['Headers']['Authorization'] = Get-WhiteboardAuthenticationHeader -Claims $claims -ForceAuthPrompt:$ForceAuthPrompt return Invoke-RestMethod @invokeRestMethodArgs } } function Get-WhiteboardAuthenticationHeader( [Parameter(Mandatory=$false)] [string]$Claims, [Parameter(Mandatory=$false)] [object]$AuthenticationToken, [Parameter(Mandatory=$false)] [switch]$ForceAuthPrompt) { if(!$AuthenticationToken) { $AuthenticationToken = Get-WhiteboardAuthenticationToken -Claims $claims -ForceAuthPrompt:$ForceAuthPrompt } return $AuthenticationToken.CreateAuthorizationHeader() } function Update-WhiteboardAuthenticationToken( [Parameter(Mandatory=$true)] [object]$AuthenticationToken) { $DateTime = (Get-Date).ToUniversalTime() $TokenExpires = ($AuthenticationToken.ExpiresOn.datetime - $DateTime).TotalMinutes # update auth token if it is close to expiry, so we have enough time to make requests if ($TokenExpires -le 5) { Write-Verbose ("Authentication Token expires in less than $TokenExpires minutes") $AuthenticationToken = Get-WhiteboardAuthenticationToken } return $AuthenticationToken } function Get-WhiteboardAuthenticationToken( [Parameter(Mandatory=$false)] [string]$Claims, [Parameter(Mandatory=$false)] [switch]$ForceAuthPrompt) { Write-Verbose "Getting authentication token for user" $whiteboardResourceId = Get-WhiteboardResourceId -Environment $env:Environment $aadAuthority = Get-AadAuthority -Environment $env:Environment [String[]]$capabilities = @("cp1") $publicClient = [Microsoft.Identity.Client.PublicClientApplicationBuilder]::Create($AdalClientId).WithAuthority($aadAuthority).WithClientCapabilities($capabilities).Build(); $promptBehavior = if ($ForceAuthPrompt -eq $true) { [Microsoft.Identity.Client.Prompt]::ForceLogin } else { [Microsoft.Identity.Client.Prompt]::NoPrompt } [String[]]$scopes = @( $whiteboardResourceId + "/.default" ); $request = $publicClient.AcquireTokenInteractive($scopes).WithPrompt($promptBehavior) if (-Not ([string]::IsNullOrEmpty($Claims))) { $request = $request.WithClaims($Claims); } $result = $request.ExecuteAsync().GetAwaiter().GetResult(); return $result; } function Get-ClaimsFromWWWAuthenticateHeader( [Parameter(Mandatory=$true)] [string]$header ) { if (!$header -or !$header.StartsWith("Bearer ")) { return $null; } $params = $header.Substring("Bearer ".length).split(@(",")) $claimsParam = $params | Where-Object {$_.TrimStart().StartsWith('claims')} if (!$claimsParam -or $claimsParam.IndexOf("=") -eq -1) { return $null; } $encodedClaims = $claimsParam.Substring($claimsParam.IndexOf("=") + 1).Trim('"') return [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($encodedClaims)) } function Get-WhiteboardHostName( [Parameter(Mandatory=$false)] [ValidateSet('Prod', 'Int', 'Dev', '')] [string] $Environment) { switch ($Environment) { 'Dev' { return "dev.whiteboard.microsoft.com"} 'Int' { return "int.whiteboard.microsoft.com"} default { return "whiteboard.microsoft.com" } } } function Get-WhiteboardResourceId( [Parameter(Mandatory=$false)] [ValidateSet('Prod', 'Int', 'Dev', '')] [string] $Environment) { switch ($Environment) { 'Int' { return "https://int.whiteboard.microsoft.com"} default { return "https://whiteboard.microsoft.com" } } } function Get-AadAuthority( [Parameter(Mandatory=$false)] [ValidateSet('Prod', 'Int', 'Dev', '')] [string] $Environment) { switch ($Environment) { 'Int' { return "https://login.windows-ppe.net/common/v2.0"} default { return "https://login.microsoftonline.com/common/v2.0" } } } |