Giter VIP home page Giter VIP logo

msal.ps's Introduction

This module is NOT supported by Microsoft

Please use higher level APIs which are officially supported:

Install from the PowerShell Gallery

Install-Module MSAL.PS

If you see the warning, You are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from 'PSGallery'?, ensure the repository is PSGallery and select Yes.

The signing certificate for MSAL.PS is changing to use Microsoft's code signing process. When upgrading to version 4.37.0.x from a previous version, you will see the following error, PackageManagement\Install-Package : Authenticode issuer 'CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US' of the new module 'MSAL.PS' with version 'x.x.x.x' from root certificate authority 'CN=Microsoft Root Certificate Authority 2011, O=Microsoft Corporation, L=Redmond, S=Washington, C=US' is not matching with the authenticode issuer 'CN=Jason Thompson, O=Jason Thompson, L=Cincinnati, S=Ohio, C=US' of the previously-installed module 'MSAL.PS' with version 'x.x.x.x' from root certificate authority 'CN=DigiCert Assured ID Root CA, OU=www.digicert.com, O=DigiCert Inc, C=US'. If you still want to install or update, use -SkipPublisherCheck parameter., which can be resolved using the following command.

Install-Module MSAL.PS -SkipPublisherCheck -Force

If you encounter the error, WARNING: The specified module 'MSAL.PS' with PowerShellGetFormatVersion '2.0' is not supported by the current version of PowerShellGet. Get the latest version of the PowerShellGet module to install this module, 'MSAL.PS', then run the following commands before attempting the MSAL.PS installation again.

## Update Nuget Package and PowerShellGet Module
Install-PackageProvider NuGet -Scope CurrentUser -Force
Install-Module PowerShellGet -Scope CurrentUser -Force -AllowClobber
## Remove old modules from existing session
Remove-Module PowerShellGet,PackageManagement -Force -ErrorAction Ignore
## Import updated module
Import-Module PowerShellGet -MinimumVersion 2.0 -Force
Import-PackageProvider PowerShellGet -MinimumVersion 2.0 -Force

If you encounter the error, WARNING: The version '1.4.7' of module 'PackageManagement' is currently in use. Retry the operation after closing the applications. then try closing your PowerShell console and reopen.

If at any point you see the error, <Path> cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170., you must enable local scripts to be run.

## Set globally on device
Set-ExecutionPolicy RemoteSigned
## Or set for just for current PowerShell session.
Set-ExecutionPolicy RemoteSigned -Scope Process

Usage and Examples

The built-in help commands in PowerShell can be used to learn about each command in the module.

## View usage examples.
Get-Help Get-MsalToken -Examples

## View full help.
Get-Help Get-MsalToken -Full

MSAL.PS

PSGallery Version PSGallery Downloads PSGallery Platform

The MSAL.PS PowerShell module wraps MSAL.NET functionality into PowerShell-friendly cmdlets and is not supported by Microsoft. Microsoft support does not extend beyond the underlying MSAL.NET library. MSAL.NET (Microsoft.Identity.Client) is an authentication library which enables you to acquire tokens from Azure AD, to access protected Web APIs (Microsoft APIs or applications registered with Azure Active Directory).

Public Client Example

$MsalToken = Get-MsalToken -ClientId '00000000-0000-0000-0000-000000000000' -Scope 'https://graph.microsoft.com/User.Read'
Invoke-RestMethod -Method Get -Uri 'https://graph.microsoft.com/v1.0/me' -Headers @{ Authorization = $MsalToken.CreateAuthorizationHeader() }

Confidential Client Example (aka Client Credential Flow) using a Certificate:

This example assumes the application has been granted relevant application permissions to obtain data from the endpoint defined in <MSGraphEndpoint>.

$ClientCertificate = Get-Item Cert:\CurrentUser\My\0000000000000000000000000000000000000000
$MsalClientApplication = Get-MsalClientApplication -ClientId '00000000-0000-0000-0000-000000000000' -ClientCertificate $ClientCertificate -TenantId '00000000-0000-0000-0000-000000000000'
$MsalToken = $MsalClientApplication | Get-MsalToken -Scope 'https://graph.microsoft.com/.default'
Invoke-RestMethod -Method Get -Uri 'https://graph.microsoft.com/v1.0/<MSGraphEndpoint>' -Headers @{Authorization = $MsalToken.CreateAuthorizationHeader() }

A client secret may be used by Get-MsalToken instead of a certificate, by constructing an object like so: $ClientSecret = 'SECRETVALUEHERE' | ConvertTo-SecureString -AsPlainText -Force and passing this to -ClientSecret rather than -ClientCertificate.

Contents

File/folder Description
build Scripts to package, test, sign, and publish the module.
src Module source code.
tests Test scripts for module.
.gitignore Define what to ignore at commit time.
README.md This README file.
LICENSE The license for the module.

Getting Started

Dependencies: MSAL.NET (Microsoft.Identity.Client)

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

msal.ps's People

Contributors

apurvghai avatar bgavrilms avatar engineererr avatar jazuntee avatar localden avatar merill avatar robinmalik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

msal.ps's Issues

Error on acquiring token with certificate

Trying to get Token by using certificate (with client id/secret works well.

$ConfidentialClientOptions = New-Object Microsoft.Identity.Client.ConfidentialClientApplicationOptions -Property @{ ClientId = $MSALRequestData.clientID; TenantId = $MSALRequestData.TenantID }
$MsalClientApplication = $ConfidentialClientOptions | Get-MsalClientApplication -ClientCertificate $MSALRequestData.Certificate
$MSALToken = $MsalClientApplication | Get-MsalToken -Scope $MSALRequestData.Scope

And here is error:

Exception calling "GetResult" with "0" argument(s): "Keyset does not exist
"
At C:\Program Files\WindowsPowerShell\Modules\MSAL.PS\4.5.1.1\Get-MsalToken.ps1:288 char:13
+             $AuthenticationResult = $AquireTokenParameters.ExecuteAsy ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : CryptographicException

Assembly conflict

Whenever I run any command in this module, I get the assembly conflict warning below:

WARNING: Assembly with same name "Microsoft.Identity.Client.Desktop.dll" is already loaded:
C:\Program Files\WindowsPowerShell\Modules\MSAL.PS\4.35.1.3\Microsoft.Identity.Client.Desktop.4.35.1\net461\Microsoft.Identity.Client.Desktop.dll

Ignore assembly conflict and continue importing module?
Some module functionality will not work.
[Y] Yes  [N] No  [?] Help (default is "N"): Y

Remember settings?
Module settings will be persisted in "C:\Users\•••••••\AppData\Roaming\MSAL.PS\config.json"
[Y] Yes  [N] No  [?] Help (default is "N"): Y

This will be remembered and not prompting within the same PowerShell window, but on a new PowerShell window, it is prompting the same warning again.

I tried providing the module settings on import, which suppressed the prompt, but the warning still shows. At least now I can schedule the script to run without stuck at the interactive prompt. But what should I do to fix this warning?
Import-Module -Name MSAL.PS -ArgumentList @{ 'dll.lenientLoading' = $true; 'dll.lenientLoadingPrompt' = $false }

Thanks,
Anson

Import-Module issue: Assembly with the same name is already loaded

Attempting to install your powershell module and unable to get it working.

I install the module using

Install-module -name MSAL.PS

I accepted the untrusted repository and accept license.

Then when I attempt to run a command

Get-MsalToken

I get the error message

Get-msaltoken: The 'Get-msaltoken' command was found in the module 'MSAL.PS', but the module could not be loaded. For more information, run 'Import-Module MSAL.PS'.

So I then attempt to import the module

Import-Module MSAL.PS -verbose

and the output is

VERBOSE: Loading module from path 'c:\Users\Me\Documents\powershell\Modules\MSAL.PS\4.16.0.3\MSAL.PS.psd1'.
VERBOSE: Loading 'Assembly' from path 'c:\Users\Me\Documents\powershell\Modules\MSAL.PS\4.16.0.3\Microsoft.Identity.Client.4.16.0\net45\Microsoft.Identity.Client.dll'.
VERBOSE: Loading 'Executable' from path 'c:\Users\Me\Documents\powershell\Modules\MSAL.PS\4.16.0.3\net45\Microsoft.Identity.Client.dll'.
VERBOSE: Loading 'Assembly' from path 'c:\Users\Me\Documents\powershell\Modules\MSAL.PS\4.16.0.3\Microsoft.Identity.Client.4.16.0\netcoreapp2.1\Microsoft.Identity.Client.dll'.
VERBOSE: Loading 'Executable' from path 'c:\Users\Me\Documents\powershell\Modules\MSAL.PS\4.16.0.3\Microsoft.Identity.Client.4.16.0\netcoreapp2.1\Microsoft.Identity.Client.dll'.
Import-Module: Assembly with same name is already loaded

I have attempted to install this on 3 different machines, attempted using PowerShell ISE, Powershell 7, and Powershell inside codespaces all return the same message.

Note: PowerShell 7 was newly installed

Is there an issue, or am I doing something wrong?

Happy to provide more information if required.

Enable-MsalTokenCacheOnDisk failing when a latest version of Microsoft.Identity.Client.dll is loaded

Enable-MsalTokenCacheOnDisk failing with error below when a latest version of Microsoft.Identity.Client.dll is loaded

Enable-MsalTokenCacheOnDisk : Cannot convert argument "tokenCache", with value: "Microsoft.Identity.Client.TokenCache", for
"EnableSerialization" to type "Microsoft.Identity.Client.ITokenCache": "Cannot convert the "Microsoft.Identity.Client.TokenCache"
value of type "Microsoft.Identity.Client.TokenCache" to type "Microsoft.Identity.Client.ITokenCache"."

There was an error loading some dependencies. DeviceCode paramter will not function.

Upgraded to v4.21.0.1 on Windows PowerShell 5.1.

Name                           Value
----                           -----
PSVersion                      5.1.19041.1
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.1
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

On module import I get the error: WARNING: There was an error loading some dependencies. DeviceCode paramter will not function.

Here is the verbose debug output

PS C:\Users\darrenjrobinson> remove-module msal.ps
PS C:\Users\darrenjrobinson> import-module msal.ps -verbose -debug
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\msal.ps.psd1'.
VERBOSE: Populating RepositorySourceLocation property for module msal.ps.
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Add-MsalClientApplication.ps1'
.
VERBOSE: Dot-sourcing the script file
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Add-MsalClientApplication.ps1'
.
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Clear-MsalTokenCache.ps1'.
VERBOSE: Dot-sourcing the script file
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Clear-MsalTokenCache.ps1'.
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\ConvertFrom-SecureStringAsPlai
nText.ps1'.
VERBOSE: Dot-sourcing the script file
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\ConvertFrom-SecureStringAsPlai
nText.ps1'.
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\ConvertTo-Dictionary.ps1'.
VERBOSE: Dot-sourcing the script file
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\ConvertTo-Dictionary.ps1'.
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Enable-MsalTokenCacheOnDisk.ps
1'.
VERBOSE: Dot-sourcing the script file
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Enable-MsalTokenCacheOnDisk.ps
1'.
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Get-MsalAccount.ps1'.
VERBOSE: Dot-sourcing the script file
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Get-MsalAccount.ps1'.
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Get-MsalClientApplication.ps1'
.
VERBOSE: Dot-sourcing the script file
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Get-MsalClientApplication.ps1'
.
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Get-MsalToken.ps1'.
VERBOSE: Dot-sourcing the script file
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Get-MsalToken.ps1'.
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\New-MsalClientApplication.ps1'
.
VERBOSE: Dot-sourcing the script file
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\New-MsalClientApplication.ps1'
.
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Remove-MsalClientApplication.p
s1'.
VERBOSE: Dot-sourcing the script file
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Remove-MsalClientApplication.p
s1'.
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Select-MsalClientApplication.p
s1'.
VERBOSE: Dot-sourcing the script file
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Select-MsalClientApplication.p
s1'.
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Select-PsBoundParameters.ps1'.
VERBOSE: Dot-sourcing the script file
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\.\Select-PsBoundParameters.ps1'.
VERBOSE: Loading module from path
'C:\Users\darrenjrobinson\Documents\WindowsPowerShell\Modules\msal.ps\4.21.0.1\MSAL.PS.psm1'.
WARNING: There was an error loading some dependencies. DeviceCode paramter will not function.
VERBOSE: Exporting function 'Add-MsalClientApplication'.
VERBOSE: Exporting function 'Clear-MsalTokenCache'.
VERBOSE: Exporting function 'ConvertFrom-SecureStringAsPlainText'.
VERBOSE: Exporting function 'ConvertTo-Dictionary'.
VERBOSE: Exporting function 'Enable-MsalTokenCacheOnDisk'.
VERBOSE: Exporting function 'Get-MsalAccount'.
VERBOSE: Exporting function 'Get-MsalClientApplication'.
VERBOSE: Exporting function 'Get-MsalToken'.
VERBOSE: Exporting function 'New-MsalClientApplication'.
VERBOSE: Exporting function 'Remove-MsalClientApplication'.
VERBOSE: Exporting function 'Select-MsalClientApplication'.
VERBOSE: Exporting function 'Select-PsBoundParameters'.
VERBOSE: Importing function 'Add-MsalClientApplication'.
VERBOSE: Importing function 'Clear-MsalTokenCache'.
VERBOSE: Importing function 'Enable-MsalTokenCacheOnDisk'.
VERBOSE: Importing function 'Get-MsalAccount'.
VERBOSE: Importing function 'Get-MsalClientApplication'.
VERBOSE: Importing function 'Get-MsalToken'.
VERBOSE: Importing function 'New-MsalClientApplication'.
VERBOSE: Importing function 'Remove-MsalClientApplication'.
VERBOSE: Importing function 'Select-MsalClientApplication'.
PS C:\Users\darrenjrobinson>

Get-MsalToken with Client Certificate fails on Windows PowerShell 5.1

The following syntax for Get-MSALToken on PowerShell 7.0.3 successfully returns an Access Token.

Get-MsalToken -ClientId $clientID -TenantId $tenantID -ClientCertificate $ClientCertificate

However it fails on Windows PowerShell 5.1 (using MSAL.PS v 4.16.0.2). I've also tested pervious versions of the MSAL.PS Module ( 4.9.0.1, 4.10.0.2 and 4.14.0.1 ) and the same error is returned. The error returned is:

Invalid provider type specified.

At line:6 char:18
+ ... cessToken = Get-MsalToken -ClientId $clientID -TenantId $tenantID -Cl ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : AuthenticationError: (Microsoft.Ident...arameterBuilder:AcquireTokenForClientParameterBuilder) [Write-Error], CryptographicException
    + FullyQualifiedErrorId : GetMsalTokenFailureAuthenticationError,Get-MsalToken

Platform info

PS C:\Users\darrenjrobinson> $psversiontable

Name                           Value
----                           -----
PSVersion                      5.1.19041.1
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.1
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

How to load in Azure Function App, and "same name" error still occurs in 4.16.0.4

Can you show how to load a specific, required version of MSAL.PS to an Azure Function App? Methods tried:

  1. In requirements.psd1, add the line: 'MSAL.PS' = '4.5.1.1' telling Azure to load this as a managed dependency. This works but has another problem: Azure will only load managed dependencies that don't require license acceptance, so 4.5.1.1 is the last such version that can be loaded this way. I need fixes that were added after 4.5.1.1.

  2. Or, in the script, add lines:
    Install-Module -Name 'MSAL.PS' -RequiredVersion '4.16.0.4' -AcceptLicense -Force
    Import-Module -Name 'MSAL.PS' -RequiredVersion '4.16.0.4'

    First run:
    2020-11-04T17:21:10.208 [Information] INFORMATION: Install-Module MSAL.PS -RequiredVersion 4.16.0.4 -AcceptLicense -Force
    2020-11-04T17:21:33.952 [Warning] WARNING: User declined to install module (MSAL.PS).
    Why would "user declined" occur if I used -AcceptLicense?

    Second run:
    System.IO.FileLoadExceptionMessage : Assembly with same name is already loaded ...
    Import-ModuleCommandOrigin : InternalScriptStackTrace : at ,
    D:\local\UserProfile\Documents\PowerShell\Modules\MSAL.PS\4.16.0.4\MSAL.PS.ps1: line 20 at ,
    D:\local\UserProfile\Documents\PowerShell\Modules\MSAL.PS\4.16.0.4\MSAL.PS.psm1: line 17
    This "already loaded" error is supposed to be fixed in 4.16.0.4, however, in this version, line 20 has had no fix applied: Add-Type -LiteralPath $RequiredAssemblies | Out-Null

There must be a way to load a version to an Azure Function App that requires license acceptance, do you know it?

Thanks,
Mark Arend

Could we enhance PowerShell engine with modern authentication

I am contributor in PowerShell Core project and my question is what could we add to PowerShell to make a support of the modern authentication better?

I can think about the alternative to Credential parameter in remoting like:

New-PSSession -MSALToken $token

Perhaps you have more thoughts how we could enhance PowerShell engine with modern authentication.

Add a timeout to the Get-MsalToken function

As a user of the module,
I would like a timeout to be added to the Get-MsalToken function,
so that when token generation fails, or the user closes the browser the function times out after a predetermined interval.

I imagine this timeout should default to 2 minutes, or something similar.

Error getting token in Interactive mode: The server understood the request, but is refusing to fulfill it

Hi,

Thanks for the great module, it's going to be of great help for us.

I am able to get a token with the same app using DeviceCode and using Client Secret but I get the error above when trying to get a token in Interactive mode. I have MFA on the account and the browser actions seems to be working, I get the error after the successfull browser popup.

Here's my command: $myAccessTokenDel = Get-MsalToken -ClientId $AzureAPPid -TenantId $tenantID -RedirectUri "https://localhost" -Interactive

Thanks in advance.

Get-MsalToken shows no output in PowerShell ISE

MSAL.PS\Get-MsalToken -ClientId 'd1ddf0e4-d672-4dae-b554-9d5bdfd93547' -DeviceCode gives no output in PowerShell ISE terminal, but it does in regular Windows PowerShell 5.1 and 7.1 from MS Store. Is it a known issue/ intended?

README does not mention this, and I found no GitHub issues on the subject.

Running Windows 10 21H1 (19043.1165) and MSAL.PS v4.35.1.3.

Screenshots

PowerShell ISE

image

PowerShell 5.1 terminal

image

PowerShell 7.1 from MS Store

image

Unable to generate tokens after updating to 4.16.0.1

I just updated my module from version 4.8.2.1 to the latest version after users reported errors, and scripts I have been using to authenticate users for delegated permissions with the authorization code flow have stopped working. I've tried running get-msaltoken with both a certificate and a secret and it sends the same errors. I've compared the parameter sets I was using in the old version with those in the new version, but I don't see any different requirements.

4.8.2.1 Parameters:

Get-MsalToken -ClientId <String> -ClientSecret <SecureString> -AuthorizationCode <String> 
[-RedirectUri <Uri>] [-TenantId <String>] [-Authority <Uri>]  
[-Scopes <String[]>] [-CorrelationId <Guid>] [-extraQueryParameters <String>] [<CommonParameters>]

4.16.0.1 Parameters:

Get-MsalToken [-ClientId] <String> -ClientSecret <SecureString> -AuthorizationCode <String> [-RedirectUri <Uri>] 
[-AzureCloudInstance {None | AzurePublic | AzureChina | AzureGermany | AzureUsGovernment}] [-TenantId <String>] 
[-Authority <Uri>] [-Scopes <String[]>] [-CorrelationId <Guid>] [-ExtraQueryParameters <Hashtable>] [<CommonParameters>]

The authorization code is received by calling the login.microsoftonline authorize endpoints with a prompt using .Net Windows objects. The code returned is then fed into the "AuthorizationCode" parameter.

Code:

$bodySplat = @{
    "ClientId" = $clientId
    "ClientSecret" = $secret
    "AuthorizationCode" = $oauth.code
    "TenantId" = $tenant
    "Authority" = $authority
    "Scopes" = $scopeAll
    "RedirectUri" = $redirectUri
}
$access = get-msaltoken @bodySplat

Error responses:

You cannot call a method on a null-valued expression.
At C:\Program Files\WindowsPowerShell\Modules\MSAL.PS\4.16.0.1\Get-MsalToken.ps1:299 char:21
+ ...             $AquireTokenParameters = $ConfidentialClientApplication.A ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
 
The variable '$AquireTokenParameters' cannot be retrieved because it has not been set.
At C:\Program Files\WindowsPowerShell\Modules\MSAL.PS\4.16.0.1\Get-MsalToken.ps1:315 char:45
+ ...            elseif ($TenantId) { [void] $AquireTokenParameters.WithAut ...
+                                            ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (AquireTokenParameters:String) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined
 
The variable '$AquireTokenParameters' cannot be retrieved because it has not been set.
At C:\Program Files\WindowsPowerShell\Modules\MSAL.PS\4.16.0.1\Get-MsalToken.ps1:316 char:42
+ ...               if ($Authority) { [void] $AquireTokenParameters.WithAut ...
+                                            ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (AquireTokenParameters:String) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined
 
The variable '$ClientApplication' cannot be retrieved because it has not been set.
At C:\Program Files\WindowsPowerShell\Modules\MSAL.PS\4.16.0.1\Get-MsalToken.ps1:319 char:86
+ ... en for Application with ClientId [{0}]' -f $ClientApplication.ClientI ...
+                                                ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (ClientApplication:String) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined
 
The variable '$AquireTokenParameters' cannot be retrieved because it has not been set.
At C:\Program Files\WindowsPowerShell\Modules\MSAL.PS\4.16.0.1\Get-MsalToken.ps1:324 char:256
+ ... lureAuthenticationError' -TargetObject $AquireTokenParameters -ErrorA ...
+                                            ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (AquireTokenParameters:String) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined
 
Invoke-RestMethod : {
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "CompactToken parsing failed with error code: 80049217",
    "innerError": {
      "date": "2020-07-08T23:55:14",
      "request-id": "6553ddab-5e6e-4b93-8ed1-12d7c7cbd916"
    }
  }
}
At H:\AppRegistration\New-TestAppGraph.ps1:75 char:5
+     Invoke-RestMethod -uri $meUri -Headers $header
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

If there's another method I should be using for the authorization code flow or something I should be doing differently, please let me know.

Examples

Please add some more examples.

Using ExtraQueryParameters for Authorization code with PKCE Flow

I'm trying to use MSAL.PS for an Authorization code with PKCE Flow.
PKCE was introduced in MSAL.NET with MSAL 4.30.0 .

Intended Process:
Initiate an interactive AuthN with PKCE parameters to get an Authorisation Code to then use to get an Access Token.

Error:

Get-MsalToken : Duplicate query parameter 'code_challenge' in extraQueryParameters. 
At line:1 char:13
+ $authCode = Get-MsalToken -ClientId $clientID `
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : AuthenticationError: (Microsoft.Ident...arameterBuilder:AcquireTokenInteractiveParameterBuilder) [Write-Error], MsalClientException
    + FullyQualifiedErrorId : GetMsalTokenFailureAuthenticationError,Get-MsalToken

Example to repo:

$authCode = Get-MsalToken -ClientId $clientID `
    -TenantId $tenantID `
    -Interactive `
    -RedirectUri $replyURL `
    -Scopes "https://graph.microsoft.com/.default" `
    -ExtraQueryParameters @{
        response_type = 'code'
        response_mode = 'query'
        state = $codeChallenge.Substring(0, 27)
        code_challenge_method = 'S256'
        code_challenge = 'M3ajh9Hx7lZqQ......4jOStyDAUyRruicBxE'
    } `
    -Verbose

Alternate:
Introduce another option with MSAL.PS to support the Authorization code with PKCE Flow.

Conditional access fails on unknown device when using Get-MsalToken with DeviceCode

I am trying to get a token using
Get-MsalToken -ClientId "xxxxx" -TenantId "xxxxx" -DeviceCode

I use Edge to go to https://microsoft.com/devicelogin, but after logging in I get the following error:
Your sign-in was successful but your admin requires the device requesting access to be managed by XXXXXXXXX to access this resource.

Looking in the Sign-Ins log in AAD, I see that the login is blocked by Conditional Access rule enforcing all logins to originate from managed AAD-joined devises. Basically, AAD does not recognize the device even though I am using Edge to login.

Is it possible to DeviceCode flow on AAD tentants blocking all logins from unmanaged devices?

Update code signing certificate

Should update the code signing certificate from Jason's personal certificate to something that aligns with the AzureAD org.

System/User Managed Assigned Service Identity Support?

I notice this does not have support for Managed Service Identity Scenarios, most common one being Azure Functions with MSI or user-assigned identity support. Is there a particular reason?

If not I can prepare a PR that integrates basically this flow:

function Get-AzMSIAccessToken {
    param (
        $Uri = 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F'
    )
    (Invoke-RestMethod  -Headers @{Metadata='true'} -UseBasicParsing -Uri $uri).access_token
}

Importing from Modules Gallery in Automation fails with message :While importing the module, an error occurred while processing the module content.

Error importing the module MSAL.PS. Import failed with the following error: Orchestrator.Shared.AsyncModuleImport.ModuleImportException: While importing the module, an error occurred while processing the module content. Internal error message: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.. at Orchestrator.Activities.SetModuleVersion.ExecuteInternal(CodeActivityContext context, String moduleName, ModuleLanguage moduleLanguage, String pythonModuleVersion, String modulePath, Guid accountId, Guid moduleVersionId, Int64 moduleContentByteSize, String storageUri, Int32 moduleVersion) at Orchestrator.Activities.SetModuleVersion.Execute(CodeActivityContext context) at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager) at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)

AADSTS50196: The server terminated an operation because it encountered a client request loop

First of all thank you for this wonderful wrapper around msal. It really helped to simplify our code. We use the following code to retrieve a valid access token:

$msalParams = @{
    ClientId              = $azureClientId
    TenantId              = $azureTenantId
    IntegratedWindowsAuth = $true
    Scopes                = "https://outlook.office.com/EWS.AccessAsUser.All"
}
$token = Get-MsalToken @msalParams

This code is invoked multiple times by different PowerShell scripts. We assume it would retrieve a valid token from the cache and if there's no valid token it will try to acquire a new token silently. However, after multiple invocations the following error is thrown:

AADSTS50196: The server terminated an operation because it encountered a client request loop. Please contact your app vendor. Trace ID: 46e48f1f-ecfc-4b82-90a1-10b591f2a500 Correlation ID: c52d4881-e115-4a02-be39-9e46686e47fc Timestamp: 2020-06-17 07:52:06Z

Looking further into this, this seems to be a reported issue at msal. A remark from @jasonnutter:

Correct, if you get this error, it is because your requests are being throttled, which is due to making too many request in a short period of time. This can be mitigated by reducing the number of tokens you are requesting, and/or ensuring that you are retrieving tokens from the cache.

Is it possible that the CmdLet Get-MsalToken is not looking into the cache but requesting a token from Azure each time on invocation?

To reproduce this issue:

(0..50) | ForEach-Object {
    $msalParams = @{
        ClientId              = $azureClientId
        TenantId              = $azureTenantId
        IntegratedWindowsAuth = $true
        Scopes                = "https://outlook.office.com/EWS.AccessAsUser.All"
    }
    $token = Get-MsalToken @msalParams
}

Optimize module for "ConstrainedLanguage"

Currently can't import module in ConstrainedLanguage mode.

PS C:\WINDOWS\system32> $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"
PS C:\WINDOWS\system32> Import-Module MSAL.PS -Verbose
VERBOSE: Loading module from path 'C:\Program Files\WindowsPowerShell\Modules\MSAL.PS\4.37.0.0\MSAL.PS.psd1'.
VERBOSE: Populating RepositorySourceLocation property for module MSAL.PS.
Import-Module : Importing *.ps1 files as modules is not allowed in ConstrainedLanguage mode.
At line:1 char:1
+ Import-Module MSAL.PS -Verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (:) [Import-Module], InvalidOperationException
    + FullyQualifiedErrorId : Modules_ImportPSFileNotAllowedInConstrainedLanguage,Microsoft.PowerShell.Commands.Import
   ModuleCommand

MSAL token provided only works with MS Graph

I have many apps registered in AD exposing apis through APIM. Trying to use the access token provided by Get-MsalToken fails validation-jwt policy in APIM. This process worked previously when using ADAL. It appears the provided token contains a header nounce that isn't standard for jwt. Is there a switch or cmdlet to pull a token via msal that isn't styled for MS Graph exclusively?

Incomplete results

Not sure if it's an issue with Graph or the module (I suspect the former) but when I run various reports I get different results returned. An example is this table which shows the amount of Teams in my organization.

image

No Teams have been deleted and if I manually check the dashboard all the Teams are still there. The Powershell script does not return an error, it simply completes without returning all the results. I've tried adding a pause between calling the next page, which helped on some scripts, but not this one.

The property 'Authority' cannot be found on this object.

Hi,

With version 4.21.0.1 I was able to run this without any issues

Get-MsalToken -TenantId $TenantId -ClientId $ClientId -Scopes "User.ReadWrite.All","Directory.ReadWrite.All" -UserCredential $Credentials

but with the release 4.37.0.0 I get suddenly this error:

**_The property 'Authority' cannot be found on this object. Verify that the property exists.
At C:\Program Files\WindowsPowerShell\Modules\MSAL.PS\4.37.0.0\Get-MsalToken.ps1:338 char:38

  • ... TenantId) { [void] $AquireTokenParameters.WithAuthority(('https://{0} ...
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [], PropertyNotFoundException
    • FullyQualifiedErrorId : PropertyNotFoundStrict_**

The ClientID is that of Microsoft Graph PowerShell (14d82eec-204b-4c2f-b7e8-296a70dab67e), and credentials are captured with Get-Credential.

I did the test within the same PS Session, same variables, simply changing the modules with -RequiredVersion during the import and I get to the error.

My Credential is a federated user identity.

Thanks for your feedback

Sincerely,
Tonino Bruno
ENGIE SA

Error using Get-MsalToken with Azure B2C Instance & custom policy

Hi,
I have a B2C instance setup with a custom sign-in policy and I am using the identity experience framework. I am trying to authenticate the user and obtain tokens via an interactive experience. I gave a try as below code.

`$ex = @{}

$ex.Add('domain_hint','myb2c.onmicrosoft.com')

$connectionDetails = @{

'ClientId'    = '5ee249ec-d5d2-43d1-9dfb-xxx911d98073'

'Interactive' = $true

'Scopes' = 'https://myb2c.onmicrosoft.com/xxxf401c-5e10-4977-b70b-721a17596de7/AllAccess'

'authority' = 'https://myb2c.onmicrosoft.com/myb2c.onmicrosoft.com/B2C_1A_signup_signin/oauth2/v2.0/authorize'

'LoginHint' = '[email protected]'

'ExtraQueryParameters' = $ex

}

$token = Get-MsalToken @connectionDetails

Write-Host $token

`
However I got error as below

Get-MsalToken : AADSTS50049: Unknown or invalid instance.
Trace ID: a01dbd69-ff03-413f-ad2e-1723f3997500
Correlation ID: 28db52d5-0ef8-4056-b5dd-61410826de9e
Timestamp: 2021-09-27 13:25:32Z
At C:\temp\Untitled2.ps1:17 char:10
$token = Get-MsalToken @connectionDetails
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : AuthenticationError: (Microsoft.Ident...arameterBuilder:AcquireTokenInteractiveParameterBuilder) [Write-Error], MsalServiceExc
eption
FullyQualifiedErrorId : GetMsalTokenFailureAuthenticationError,Get-MsalToken

Is this flow supported? If so could anybody please help me with this? If there are any e.g. on these lines it would be great. I am using the latest 4.36 version of MSAL.PS

Update: If I change the authority url to as 'https://myb2c.onmicrosoft.com/tfp/467xxx97-0c7c-4648-9569-75e51a9967d5/B2C_1A_signup_signin' I get the below error

Get-MsalToken : A authority of type Aad was used at the application and of type B2C at the request level. Please use the same authority type between the
two.
At C:\temp\Untitled2.ps1:17 char:10
$token = Get-MsalToken @connectionDetails

CategoryInfo          : AuthenticationError: (Microsoft.Ident...arameterBuilder:AcquireTokenInteractiveParameterBuilder) [Write-Error], MsalClientExce 
   ption
FullyQualifiedErrorId : GetMsalTokenFailureAuthenticationError,Get-MsalToken

DLL Mismatch with Az.Accounts

The new version of Az.Accounts is throwing up this error "WARNING: INITIALIZATION: Fallback context save mode to process because of error during checking token cache persistence: Could not load file or assembly 'Microsoft.Identity.Client, Version=4.23.0.0, Culture=neutral, PublicKeyToken=0a613f4dd989e8ae'. Could not find or load a specific file. (0x80131621)." when doing a connect-AzAccount.

When I look at what assemblies are loaded using [System.AppDomain]::CurrentDomain.GetAssemblies() | Where {$_.location -like "identity"} | FL I can see a previous DLL loaded from MSAL.PS PowerShell/Modules/MSAL.PS/4.21.0.1/Microsoft.Identity.Client.4.21.0/netcoreapp2.1/Microsoft.Identity.Client.dll

Is it possible to update the dependency or advise on how I can fix. I tried removing the modules and installing Az.Accounts first but that has not fixed it.

Failure to obtain token with ConfidentialClient - Azure Government

Get-MsalToken -ClientId '' -TenantId '' -ClientSecret (read-host -AsSecureString) -AzureCloudInstance AzureUsGovernment

No matter the permutation here I seem to keep getting the following error:

Get-MsalToken :
 The application is configured for cloud login.microsoftonline.com and the request for a different cloud -
login.microsoftonline.us. This is not supported - the app and the request must target the same cloud.
See https://aka.ms/msal-net-authority-override for details
At line:1 char:1
+ Get-MsalToken -ClientId  -TenantI ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : AuthenticationError: (Microsoft.Ident...arameterBuilder:AcquireTokenForClientParameterBu
   ilder) [Write-Error], MsalClientException
    + FullyQualifiedErrorId : GetMsalTokenFailureAuthenticationError,Get-MsalToken

Version History Notes

Is there any notes that describe the changes with each version? Currently on 4.10.0.2 but not sure what changed between that version and the current version 4.16.0.2.

Adjust the resource parameter in the oauth2/token request

Hi everyone,

is it possible to somehow adjust the resource used to acquire the token ?

When I use postman I am able to do something like

grant_type=client_credentials&
client_id=FOO&
client_secret=BAR&
resource=https://vault.azure.net

And then I receive an access token which I can use to call Azure Key Vault related rest APIs e.g. GetKey

I saw that I can adjust the scope in MSAL.PS when I call the

Get-MsalToken $clientApplication -Scopes 'https://vault.azure.net/.default'

But after giving this scope I receive the error

Invoke-RestMethod : {
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure. Invalid audience.",
    "innerError": {
      "date": "2021-02-26T07:33:39",
      "request-id": "157067be-77a3-4c85-b31e-7e4f5249e00c",
      "client-request-id": "157067be-77a3-4c85-b31e-7e4f5249e00c"
    }
  }
}

In postman I was able to resolve this error by adjusting the resource. But I am not able to find this configuration in MSAL.PS.

Thank you very much for your help.

AADSTS50196: The server terminated an operation because it encountered a client request loop

Hi,

I use your module to acquire an access token to consult the MS Graph API which is working great, but when I run my script I bump into the following error after the 5th entry being processed:

AADSTS50196: The server terminated an operation because it encountered a client request loop

What I am doing is essentially the following in a Function:

    $MyVarAccessToken = Get-MsalToken -ClientId $ClientID -TenantId $TenantID -UserCredential $MyVarPSCredentials
    $MyVarAuthHeader = @{
        Authorization = $MyVarAccessToken.CreateAuthorizationHeader()
        UserAgent = $UserAgent
    }

And in my script body I just call the function for each object I want to query.

Isn't it possible to use the cached token until its about to expire?

ps: thanks for your great module!

Function App system assigned managed identity does not work

Function App system assigned managed identity does not work with MSAL.PS in lastest version.

Because "Microsoft.Identity.Client.dll" is already loaded in the core app.

It would be necessary to detect the execution in a function app so that the libraries are not loaded

Thank's ;-)

Exception calling "ExecuteAsync" with "0" argument(s): "No account or login hint was passed to the AcquireTokenSilent call.

First of all thank you for this wonderful wrapper around msal, it really helped simplifying some of our code. Retrieving a token works flawless like this:

$msalParams = @{
    ClientId = $azureClientId
    TenantId = $azureTenantId 
    Scopes   = "https://outlook.office.com/EWS.AccessAsUser.All"
}
$token = Get-MsalToken @msalParams

But for longer running scripts and calling this CmdLet multiple times we sometimes get this error message:

No account or login hint was passed to the AcquireTokenSilent call.
Exception calling "ExecuteAsync" with "0" argument(s): "No account or login hint was passed to the AcquireTokenSilent call."

After some investigation I found a similar treat here but I can't seem to make the error disappear. Are we doing something wrong?

Thank you for your help.

No Refresh Token returned from Get-MSALToken using DeviceCode flow

Get-MsalToken -ClientId $global:myDevCred.UserName -DeviceCode -Interactive -TenantId $global:myDevTenantId -RedirectUri "https://localhost" returns and Access Token but no Refresh Token.

I suspect this is associated with functionality leveraged from Microsoft.Identity.Client.dll as I can't see anything specifically in MSAL.PS that would not provide the Refresh Token.

Writing a simple PowerShell function using the Device Code flow (without leveraging Microsoft.Identity.Client.dll) using the same Registered Application DOES return a Refresh Token.

Is there anyway to force MSAL.PS to return a Refresh Token for the Device Code flow?
Device Code flow is required as the permissions required for the app aren't available as App Permissions, just Delegated Permissions.

Get-MsalToken interactive fails on PowerShell 7

I have tried using Get-MsalToken -interactive in PowerShell 7.03 and PowerShell 7.1 preview 7 and it fails with the following error.

image

It launches the browser successfully and I can see the code is returned however the error is then returned.
image

When I run the same command from PowerShell 5.1 it completes successfully and I get the token back. Any help is appreciated.

Interactive JWT flow with extra claims

It is not clear on how to get a JWT with extra claims from an on prem ADFS2019 (non-azure integrated) server.

https://adfs.fqdn/adfs/oauth2/authorize?response_type=id_token&client_id={0}&resource={1}&redirect_uri={2}&response_mode=form_post

The above is able to work for using a POST with the body containing FormsAuthentication/username/password. Trying to move away from the custom written library and move to MSAL.PS to support interactive sessions to do username/password/+MFA authentication.

Get-MsalToken fails when run as another user

When running Get-MSALToken in a PowerShell session run as a user other than the currently logged on user, a blank popup is shown and a separate error prompt appears:

"We couldn't create the data directory.
Microsoft Edge can't read and write to its data directory:
C:\Users\ABCD/.msal/web2view/data/EBWebView"

Missing function for fetching group members using msal token

Reporting an Issue or Missing Feature
Missing or unable to find function to fetch group members using MSAL token and 'Get-AzureADGroupMembers' does not work since it works for aad graph access only and not on msal graph access.

  1. Get-AzureADMSGroup command is working
  2. Get-AzureADGroupMembers not working displays below error.

Expected behavior
Should have function to fetch groupmembers using msal token.

Actual behavior
Unable to fetch members of group and failed with error
image

Steps to reproduce behavior
`$azureAplicationId = "xxx"
$azureTenantId = "xxx"
$azurePassword = ConvertTo-SecureString "xxx" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Connect-AzAccount -Credential $psCred -Tenant $azureTenantId -ServicePrincipal

$context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
$aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.windows.net").AccessToken
$connectionDetails = @{
    'TenantId'     = 'xxx'
    'ClientId'     = 'xxx'
    'ClientSecret' = 'xxx' | ConvertTo-SecureString -AsPlainText -Force
}

$mstoken = Get-MsalToken @connectionDetails
Connect-AzureAD -AadAccessToken $aadToken -MsAccessToken $mstoken.AccessToken -AccountId $context.Account.Id -TenantId 
$context.tenant.id;
$group = Get-AzureADMSGroup -Filter "Mail eq 'xxx'" # where xxx is group email id
$groupMembers += Get-AzureADGroupMember -ObjectId $group.Id `

Device Code grant flow working in Get-MsalToken

I noticed you have parameters commented out for making use of the Device Code flow in Get-MsalToken.ps1. I am very interested in using this feature so that I can easily get tokens with Delegated permissions for a script running on a headless server.

        # [Parameter(Mandatory=$true, ParameterSetName='PublicClient-DeviceCode')]
        # [Parameter(Mandatory=$false, ParameterSetName='PublicClient-InputObject')]
        # [switch] $DeviceCode,

Error: Get-MsalToken : Cannot convert 'System.Object[]' to the type 'System.Exception' required by parameter 'Exception'. Specified method is not supported.

I am starting to get these errors occasionally.
I use the disk cache, but clearing the disk cache does not resolve it.

PS> $token = Get-GraphDelegatedToken -ApplicationID $clientid -Verbose:$false
Get-MsalToken : Cannot convert 'System.Object[]' to the type 'System.Exception' required by parameter 'Exception'. Specified method is not supported.
At C:\ps\data\local\modules\msal.ps\4.37.0.0\Get-MsalToken.ps1:293 char:49
+ ... ionResult = Get-MsalToken -Silent -PublicClientApplication $PublicCli ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-MsalToken], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Get-MsalToken

I've been able to temporarily work around this issue by changing this line 299 on get-msaltoken from:

catch [Microsoft.Identity.Client.MsalUiRequiredException] {

to:

catch  {

I know that probably isn't a valid fix, but it at least gets me going and might help others. I haven't noticed any negative side-effects.

Get-MsalToken -AzureCloudInstance not working

when using Get-Msaltoken -ClientId XXXXXX -TenantId xxxxxxx -AzureCloudInstance AzureUSGovernment
a Sign in to your account windows pops up and I pick my account > which goes to taking you to your orgs sign in page > but it errors with AADSTS50011: The URL specified in the request does not match the reply URLs configured for the application

should this work with all Gov clouds GCC, GCCH, DOD ?

MSAL.PS 4.14.0.1 and X5C

I looked at the source code of MSAL.PS version 4.14.0.1 and searched for "x5c". I see all occurrences have been commented:

#
# [Parameter(Mandatory=$true, ParameterSetName='ConfidentialClientCertificate')]
# [Parameter(Mandatory=$true, ParameterSetName='ConfidentialClientCertificate-AuthorizationCode')]
# [Parameter(Mandatory=$true, ParameterSetName='ConfidentialClientCertificate-OnBehalfOf')]
# [switch] $SendX5C,

#if ($SendX5C) { [void] $AquireTokenParameters.WithSendX5C($SendX5C) }

Why? Is there a (pre-release) version where it's not/

IntegratedWindowsAuth example?

New to oauth, hope I'm asking the question correctly. I feel like I'm really close but...
I registered the app in azure, and when I get a token using this code:

$scope = @("https://outlook.office365.com/.default") $msalParams = @{ ClientId = $azureClientId TenantId = $azureTenantId Scopes = $scope RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient" } $token = Get-MsalToken @msalParams

I'm prompted to login with an account that has access to the Exchange mailbox I'm working on. The generated token works!! It comes back with all the assigned scopes, and I figured out how to refresh the token with -silent. Amazing!!

I would really like to avoid the login prompt, use the "currently logged in user" (Running as a service account)
When I try with client secret, the token I get back doesn't have the scopes or IDToken properties, etc. And that token doesn't get me to the resources I need in EWS.

I've been searching for examples but I can't find anything about how to either pass credentials to get-msalToken as a variable or somehow inherit the "windows login session token" (I'm making that term up) for the currently logged in user. I think I would use IntegratedWindowsAuth property but I don't know what I hand that property or what other fields need to be used.
Can anyone help or point me to a simple example? Perhaps I need to change a property on the azure app registration or....

Thanks!! Fred

Customize or close default browser window after successful authentication

When acquiring a token with Get-MsalToken (latest version) using the default browser, a browser window stays open.

This windows shows the RedirectionUri as address (http://localhost:62867/?code=...), and the site contains only the text "Authentication complete. You can return to the application. Feel free to close this browser tab.".

This window does not contain any information which application asks for logon data and for what reasons.

Is there a way to customize this browser window, to add information to it or to close it automatically?

If there is currently no way in MSAL.PS, but in MSAL itself, I would like to propose this as a new feature for MSAL.PS.

Thanks in advance!

When will be MSAL PowerShell script will be released for latest Microsoft.Identity.Client 4.7 packages?

Please let us know when will be MSAL PowerShell scripts will be released for 4.7 packages. Currently the packages which are there for MSAL.PS of version 4.5.x are throwing errors with latest Microsoft.Identity.Client.dll. Following is the sample error which we are getting:

Script Used:
Get-MSALToken -Scopes "user.read" -ClientId "<app id>" -RedirectUri "urn:ietf:wg:oauth:2.0:oob" -Interactive

Error:
Exception calling "GetResult" with "0" argument(s): "The process has no package identity. (Exception from HRESULT: 0x80073D54)" At C:\Program Files\WindowsPowerShell\Modules\MSAL.PS\4.5.1.1\Get-MsalToken.ps1:288 char:13 $AuthenticationResult = $AquireTokenParameters.ExecuteAsy ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CategoryInfo : NotSpecified: (:) [], MethodInvocationException FullyQualifiedErrorId : InvalidOperationException

We also do not have any good samples in PowerShell for using MSAL libraries to get the access token in NativeClient approach with out using ClientSecret and asking the user to provide login screen to provide his credentials (Interactive mode).

Thanks,
Venu

Customize account selection/logon window

When acquiring a token with Get-MsalToken (latest version) without a LoginHint, the user gets presented a browser window with the option to select one of the already logged-in accounts or to log in with another account.

This window does not contain any information which application asks for logon data and for what reasons.

Is there a way to customize this browser windows or to add information to it?

If there is currently no way in MSAL.PS, but in MSAL itself, I would like to propose this as a new feature for MSAL.PS.

Thanks in advance!

ERROR: Assembly with same name is already loaded when running in Azure Function

I'm trying to get this to work in a Azure Powershell function (httptrigger)

Test code I have is the following

Import-Module MSAL.PS

$TenantId = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$ClientId = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$CertThumbPrint = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

$connectionDetails = @{
    'TenantId'          = $TenantId
    'ClientId'          = $ClientId
    'ClientCertificate' = Get-Item -Path "Cert:\CurrentUser\My\$CertThumbPrint"
}

$Token = Get-MsalToken @connectionDetails

Local in vs code debug it works fine.
However, when testing this code in Azure I get the following error

2021-03-24T15:52:24.871 [Error] ERROR: Assembly with same name is already loadedException :Type : System.IO.FileLoadExceptionMessage : Assembly with same name is already loadedTargetSite :Name : LoadFromPathDeclaringType : System.Runtime.Loader.AssemblyLoadContextMemberType : MethodModule : System.Private.CoreLib.dllStackTrace :at System.Runtime.Loader.AssemblyLoadContext.LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, String ilPath, String niPath, ObjectHandleOnStack retAssembly)at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)

I have MSAL.PS 4.21.0.1 included in the Modules folder of the project

Any clue what might be causing this issue and how to resolve it?

Unable to authenticate interactively.

Hello,

I am trying to acquire an MSAL Oauth token from Azure AD, scoped to Yammer API. Since Yammer REST APIs now support the MSAL:

We’re excited to inform that all Yammer v1 APIs now support the usage of Azure Active Directory (AAD) tokens.

I was hoping that I will be able to use MSAL.PS to acquire the AAD token and use it in my PowerShell scripts. However, Yammer APIs only support delegated permissions and not application permissions, as is documented in the same article cited above:

Choose Delegated permissions and user_impersonation. Application permissions are currently not supported and we’re planning on addressing that limitation.

This is why, I will need to use interactive authentication when invoking MSAL.PS. This is why I run the following script:

$TenantId='Tenant ID'
$ClientId='Client ID'
$Scopes=@('https://api.yammer.com/.default')
$token=Get-MsalToken -TenantId $TenantId -ClientId $ClientId -Scopes $Scopes -Interactive -Loginhint 'UserName'

When I run the above mentioned script, I do get the prompt to login and after that, I get the following error:

image

Following the URL; https://aka.ms/msal-net-invalid-client, I did make my application public:

image

But despite making the change, I continue to get the same error. It is important to add that scoping the script to Yammer API isn’t the problem here, because, if I scope it to Microsoft Graph API, with the script below, I get the same error:

Get-MsalToken -ClientId $clientid -TenantId $tenantid -Interactive -Scope 'https://graph.microsoft.com/User.Read' -LoginHint '[email protected]'

I should mention that my application supports delegated permission for Yammer and Microsoft Graph:
image

image

Just to add, I am able to acquire an AAD Token and call the Yammer REST API successfully, if I bypass MSAL.PS completely, using the script below. However, it isn’t as secure as MSAL.PS/NET and doesn’t allow me the advantage of caching the token and refreshing it when expired:

$username=Read-Host "Enter the UserName"
$password=Read-Host "Enter the password"
$ClientID="Client ID"
$loginURL="https://login.microsoftonline.com"
$tenantdomain="Tenant Name.onmicrosoft.com"
$scope="https://api.yammer.com/.default"
$body = @{grant_type="password";scope=$scope;client_id=$ClientID;username=$username;password=$password}
$oauth = Invoke-RestMethod -Method Post -Uri $("$loginURL/$tenantdomain/oauth2/v2.0/token") -Body $body
$password=$null
$Bearertoken=$oauth.access_token
$headers = @{Authorization="Bearer $Bearertoken"}
$response=Invoke-RestMethod -Method Get -Uri "https://www.yammer.com/api/v1/users/current.json” -Headers $headers
$response |FT Type, ID, Network_Id, Full_Name, Job_Title, Email

Hence, my ask is, is there a bug when invoking interactive authentication for MSAL.PS?

P.S(pun intended): I did see closed issues for similar problems, which may not have been as elaborate as it could have. So, I wanted to share as much detail as possible. If there’s any additional data needed, please let me know. Thanks in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.