Skip to content
This repository has been archived by the owner on Sep 22, 2023. It is now read-only.

Added param AsSecureString #77

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/Get-MsalToken.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,13 @@
PS C:\>$MsalClientApplication = Get-MsalClientApplication -ClientId '00000000-0000-0000-0000-000000000000' -ClientCertificate $ClientCertificate -TenantId '00000000-0000-0000-0000-000000000000'
PS C:\>$MsalClientApplication | Get-MsalToken -Scopes 'https://graph.microsoft.com/.default'
Pipe in confidential client options object to get a confidential client application using a client certificate and target a specific tenant.
.EXAMPLE
PS C:\>$MsalToken = Get-MsalToken -ClientId '00000000-0000-0000-0000-000000000000' -Scopes 'https://graph.microsoft.com/User.Read','https://graph.microsoft.com/Files.ReadWrite' -AsSecureString
PS C:\>Connect-MgGraph -AccessToken $MsalToken.AccessTokenAsSecureString()
Get AccessToken and allow to convert to SecureString. Makes it easier to work with Microsoft.Graph SDK 2.0 - AccessToken param now is SecureString.
#>
function Get-MsalToken {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")]
[CmdletBinding(DefaultParameterSetName = 'PublicClient')]
[OutputType([Microsoft.Identity.Client.AuthenticationResult])]
param
Expand Down Expand Up @@ -201,7 +206,11 @@ function Get-MsalToken {

# Specifies the timeout threshold for MSAL.net operations.
[Parameter(Mandatory = $false)]
[timespan] $Timeout
[timespan] $Timeout,

# Convert tokens to SecureString.
[Parameter(Mandatory = $false)]
[switch] $AsSecureString
)

begin {
Expand Down Expand Up @@ -380,13 +389,27 @@ function Get-MsalToken {
else {
$AuthenticationResult = $taskAuthenticationResult.Result
}

}
catch {
Write-Error -Exception (Coalesce $_.Exception.InnerException,$_.Exception) -Category ([System.Management.Automation.ErrorCategory]::AuthenticationError) -CategoryActivity $MyInvocation.MyCommand -ErrorId 'GetMsalTokenFailureAuthenticationError' -TargetObject $AquireTokenParameters -ErrorAction Stop
}
break
}
}

if($AsSecureString) {
try {
$AccessTokenSecureString = { ConvertTo-SecureString -AsPlainText $this.AccessToken -Force }
$AuthenticationResult | Add-Member -MemberType ScriptMethod -Name AccessTokenAsSecureString -Value $AccessTokenSecureString
}
catch {}
try {
$IdTokenSecureString = { ConvertTo-SecureString -AsPlainText $this.IdToken -Force }
$AuthenticationResult | Add-Member -MemberType ScriptMethod -Name IdTokenAsSecureString -Value $IdTokenSecureString
}
catch {}
}

return $AuthenticationResult
}
Expand Down