Azure / azure-powershell

Microsoft Azure PowerShell
Other
4.26k stars 3.86k forks source link

Connect-AzAccount fails to use a valid SAS token passed into the AccessToken parameter #12544

Closed Paqi closed 4 years ago

Paqi commented 4 years ago

Description

I want to use Connect-AzAccount to connect to my APIM tenant. I'm using the parameter set that uses AccessToken and AccountId. I'm generating a SAS Token that I'm passing into the AccessToken parameter, and I'm passing in the string of the AccountId for my APIM tenant. I looked up the AccountId on this page: https://resources.azure.com/

When I run my script, I encounter an error that reads: Connect-AzAccount : The access token is invalid.

I'm sure the generated SAS Token is valid, because I'm able to successfully use it in the Authorization header of this APIM REST API request: https://{APIM TENANT NAME}.azure-api.net/loggers/?api-version=2017-03-01

Steps to reproduce

$tenant_management_key=$args[0]
Write-Output "key:"
Write-Output $tenant_management_key
$keyBytes = [Text.Encoding]::UTF8.GetBytes($tenant_management_key)
$encoder = New-Object System.Security.Cryptography.HMACSHA512
$encoder.Key = $keyBytes

$id = "integration"
$Expires =[DateTime]::UtcNow.AddMinutes(10).ToString('o', [System.Globalization.CultureInfo].InvariantCulture)
$dataToSign = $id + "`n" + $Expires
$dataToSignBytes = [Text.Encoding]::UTF8.GetBytes($dataToSign)
$hash = $encoder.ComputeHash($dataToSignBytes)
$encoder.Dispose()

$signature = [Convert]::ToBase64String($hash)
$sasToken = "SharedAccessSignature uid=" + $id + "&ex=" + $Expires + "&sn=" + $signature
Write-Output "sasToken:"
Write-Output $sasToken

$accountId=$args[1]
Write-Output "accountId:"
Write-Output $accountId
Import-Module Az.Accounts
Connect-AzAccount -AccessToken $sasToken -AccountId $accountId

Environment data

$PSVersionTable

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

Module versions

Get-Module -ListAvailable

    Directory: C:\Program Files\WindowsPowerShell\Modules

ModuleType Version    Name                                ExportedCommands                                                                                                                                                                                       
---------- -------    ----                                ----------------                                                                                                                                                                                       
Binary     1.4.81     APIManagementTemplate               {Get-ParameterTemplate, Write-APIManagementTemplates, Get-APIManagementTemplate}                                                                                                                       
Script     1.9.1      Az.Accounts                         {Disable-AzDataCollection, Disable-AzContextAutosave, Enable-AzDataCollection, Enable-AzContextAutosave...}                                                                                            
Script     5.3.0      Azure                               {Get-AzureAutomationCertificate, Get-AzureAutomationConnection, New-AzureAutomationConnection, Remove-AzureAutomationConnection...}                                                                    
Script     1.0.1      Microsoft.PowerShell.Operation.V... {Get-OperationValidation, Invoke-OperationValidation}                                                                                                                                                  
Binary     1.0.0.1    PackageManagement                   {Find-Package, Get-Package, Get-PackageProvider, Get-PackageSource...}                                                                                                                                 
Script     3.4.0      Pester                              {Describe, Context, It, Should...}                                                                                                                                                                     
Script     1.0.0.1    PowerShellGet                       {Install-Module, Find-Module, Save-Module, Update-Module...}                                                                                                                                           
Script     2.0.0      PSReadline                          {Get-PSReadLineKeyHandler, Set-PSReadLineKeyHandler, Remove-PSReadLineKeyHandler, Get-PSReadLineOption...}                                                                                             

    Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules

ModuleType Version    Name                                ExportedCommands                                                                                                                                                                                       
---------- -------    ----                                ----------------                                                                                                                                                                                       
Manifest   1.0.0.0    AppBackgroundTask                   {Disable-AppBackgroundTaskDiagnosticLog, Enable-AppBackgroundTaskDiagnosticLog, Set-AppBackgroundTaskResourcePolicy, Unregister-AppBackgroundTask...}                                                  
Manifest   2.0.0.0    AppLocker                           {Get-AppLockerFileInformation, Get-AppLockerPolicy, New-AppLockerPolicy, Set-AppLockerPolicy...}                                                                                                       
Manifest   1.0.0.0    AppvClient                          {Add-AppvClientConnectionGroup, Add-AppvClientPackage, Add-AppvPublishingServer, Disable-Appv...}                                                                                                      
Manifest   2.0.1.0    Appx                                {Add-AppxPackage, Get-AppxPackage, Get-AppxPackageManifest, Remove-AppxPackage...}                                                                                                                     
Manifest   1.0        BestPractices                       {Get-BpaModel, Get-BpaResult, Invoke-BpaModel, Set-BpaResult}                                                                                                                                          
Manifest   2.0.0.0    BitsTransfer                        {Add-BitsFile, Complete-BitsTransfer, Get-BitsTransfer, Remove-BitsTransfer...}                                                                                                                        
Manifest   1.0.0.0    BranchCache                         {Add-BCDataCacheExtension, Clear-BCCache, Disable-BC, Disable-BCDowngrading...}                                                                                                                        
Manifest   1.0.0.0    CimCmdlets                          {Get-CimAssociatedInstance, Get-CimClass, Get-CimInstance, Get-CimSession...}                                                                                                                          
Manifest   1.0        ConfigCI                            {Get-SystemDriver, New-CIPolicyRule, New-CIPolicy, Get-CIPolicy...}                                                                                                                                    
Manifest   1.0        Defender                            {Get-MpPreference, Set-MpPreference, Add-MpPreference, Remove-MpPreference...}                                                                                                                         
Manifest   1.0.1.0    DeliveryOptimization                {Get-DeliveryOptimizationStatus, Get-DeliveryOptimizationPerfSnap, Get-DeliveryOptimizationLog, Get-DOConfig...}                                                                                       
Binary     2.0.0.0    DFSR                                {New-DfsReplicationGroup, Get-DfsReplicationGroup, Set-DfsReplicationGroup, Remove-DfsReplicationGroup...}                                                                                             
Manifest   1.0.0.0    DirectAccessClientComponents        {Disable-DAManualEntryPointSelection, Enable-DAManualEntryPointSelection, Get-DAClientExperienceConfiguration, Get-DAEntryPointTableItem...}                                                           
Script     3.0        Dism                                {Add-AppxProvisionedPackage, Add-WindowsDriver, Add-WindowsCapability, Add-WindowsImage...}                                                                                                            
Manifest   1.0.0.0    DnsClient                           {Resolve-DnsName, Clear-DnsClientCache, Get-DnsClient, Get-DnsClientCache...}                                                                                                                          
Manifest   1.0.0.0    EventTracingManagement              {Start-EtwTraceSession, New-EtwTraceSession, Get-EtwTraceSession, Update-EtwTraceSession...}                                                                                                           
Manifest   2.0.0.0    International                       {Get-WinDefaultInputMethodOverride, Set-WinDefaultInputMethodOverride, Get-WinHomeLocation, Set-WinHomeLocation...}                                                                                    
Manifest   1.0.0.0    iSCSI                               {Get-IscsiTargetPortal, New-IscsiTargetPortal, Remove-IscsiTargetPortal, Update-IscsiTargetPortal...}                                                                                                  
Manifest   2.0.0.0    IscsiTarget                         {Add-ClusteriSCSITargetServerRole, Add-IscsiVirtualDiskTargetMapping, Checkpoint-IscsiVirtualDisk, Convert-IscsiVirtualDisk...}                                                                        
Script     1.0.0.0    ISE                                 {New-IseSnippet, Import-IseSnippet, Get-IseSnippet}                                                                                                                                                    
Manifest   1.0.0.0    Kds                                 {Add-KdsRootKey, Get-KdsRootKey, Test-KdsRootKey, Set-KdsConfiguration...}                                                                                                                             
Manifest   1.0.1.0    Microsoft.PowerShell.Archive        {Compress-Archive, Expand-Archive}                                                                                                                                                                     
Manifest   3.0.0.0    Microsoft.PowerShell.Diagnostics    {Get-WinEvent, Get-Counter, Import-Counter, Export-Counter...}                                                                                                                                         
Manifest   3.0.0.0    Microsoft.PowerShell.Host           {Start-Transcript, Stop-Transcript}                                                                                                                                                                    
Manifest   1.0.0.0    Microsoft.PowerShell.LocalAccounts  {Add-LocalGroupMember, Disable-LocalUser, Enable-LocalUser, Get-LocalGroup...}                                                                                                                         
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Content, Clear-Content, Clear-ItemProperty, Join-Path...}                                                                                                                                         
Script     1.0        Microsoft.PowerShell.ODataUtils     Export-ODataEndpointProxy                                                                                                                                                                              
Manifest   3.0.0.0    Microsoft.PowerShell.Security       {Get-Acl, Set-Acl, Get-PfxCertificate, Get-Credential...}                                                                                                                                              
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Format-List, Format-Custom, Format-Table, Format-Wide...}                                                                                                                                             
Manifest   3.0.0.0    Microsoft.WSMan.Management          {Disable-WSManCredSSP, Enable-WSManCredSSP, Get-WSManCredSSP, Set-WSManQuickConfig...}                                                                                                                 
Manifest   1.0        MMAgent                             {Disable-MMAgent, Enable-MMAgent, Set-MMAgent, Get-MMAgent...}                                                                                                                                         
Manifest   1.0.0.0    MsDtc                               {New-DtcDiagnosticTransaction, Complete-DtcDiagnosticTransaction, Join-DtcDiagnosticResourceManager, Receive-DtcDiagnosticTransaction...}                                                              
Manifest   2.0.0.0    NetAdapter                          {Disable-NetAdapter, Disable-NetAdapterBinding, Disable-NetAdapterChecksumOffload, Disable-NetAdapterEncapsulatedPacketTaskOffload...}                                                                 
Manifest   1.0.0.0    NetConnection                       {Get-NetConnectionProfile, Set-NetConnectionProfile}                                                                                                                                                   
Manifest   1.0.0.0    NetDiagnostics                      Get-NetView                                                                                                                                                                                            
Manifest   1.0.0.0    NetEventPacketCapture               {New-NetEventSession, Remove-NetEventSession, Get-NetEventSession, Set-NetEventSession...}                                                                                                             
Manifest   2.0.0.0    NetLbfo                             {Add-NetLbfoTeamMember, Add-NetLbfoTeamNic, Get-NetLbfoTeam, Get-NetLbfoTeamMember...}                                                                                                                 
Manifest   1.0.0.0    NetNat                              {Get-NetNat, Get-NetNatExternalAddress, Get-NetNatStaticMapping, Get-NetNatSession...}                                                                                                                 
Manifest   2.0.0.0    NetQos                              {Get-NetQosPolicy, Set-NetQosPolicy, Remove-NetQosPolicy, New-NetQosPolicy}                                                                                                                            
Manifest   2.0.0.0    NetSecurity                         {Get-DAPolicyChange, New-NetIPsecAuthProposal, New-NetIPsecMainModeCryptoProposal, New-NetIPsecQuickModeCryptoProposal...}                                                                             
Manifest   1.0.0.0    NetSwitchTeam                       {New-NetSwitchTeam, Remove-NetSwitchTeam, Get-NetSwitchTeam, Rename-NetSwitchTeam...}                                                                                                                  
Manifest   1.0.0.0    NetTCPIP                            {Get-NetIPAddress, Get-NetIPInterface, Get-NetIPv4Protocol, Get-NetIPv6Protocol...}                                                                                                                    
Manifest   1.0.0.0    NetworkConnectivityStatus           {Get-DAConnectionStatus, Get-NCSIPolicyConfiguration, Reset-NCSIPolicyConfiguration, Set-NCSIPolicyConfiguration}                                                                                      
Manifest   1.0.0.0    NetworkSwitchManager                {Disable-NetworkSwitchEthernetPort, Enable-NetworkSwitchEthernetPort, Get-NetworkSwitchEthernetPort, Remove-NetworkSwitchEthernetPortIPAddress...}                                                     
Manifest   1.0.0.0    NetworkTransition                   {Add-NetIPHttpsCertBinding, Disable-NetDnsTransitionConfiguration, Disable-NetIPHttpsProfile, Disable-NetNatTransitionConfiguration...}                                                                
Manifest   1.0        NFS                                 {Get-NfsMappedIdentity, Get-NfsNetgroup, Install-NfsMappingStore, New-NfsMappedIdentity...}                                                                                                            
Manifest   1.0.0.0    PcsvDevice                          {Get-PcsvDevice, Start-PcsvDevice, Stop-PcsvDevice, Restart-PcsvDevice...}                                                                                                                             
Binary     1.0.0.0    PersistentMemory                    {Get-PmemDisk, Get-PmemPhysicalDevice, Get-PmemUnusedRegion, New-PmemDisk...}                                                                                                                          
Manifest   1.0.0.0    PKI                                 {Add-CertificateEnrollmentPolicyServer, Export-Certificate, Export-PfxCertificate, Get-CertificateAutoEnrollmentPolicy...}                                                                             
Manifest   1.0.0.0    PlatformIdentifier                  Get-PlatformIdentifier                                                                                                                                                                                 
Manifest   1.0.0.0    PnpDevice                           {Get-PnpDevice, Get-PnpDeviceProperty, Enable-PnpDevice, Disable-PnpDevice}                                                                                                                            
Manifest   1.1        PrintManagement                     {Add-Printer, Add-PrinterDriver, Add-PrinterPort, Get-PrintConfiguration...}                                                                                                                           
Binary     1.0.11     ProcessMitigations                  {Get-ProcessMitigation, Set-ProcessMitigation, ConvertTo-ProcessMitigationPolicy}                                                                                                                      
Manifest   1.1        PSDesiredStateConfiguration         {Set-DscLocalConfigurationManager, Start-DscConfiguration, Test-DscConfiguration, Publish-DscConfiguration...}                                                                                         
Script     1.0.0.0    PSDiagnostics                       {Disable-PSTrace, Disable-PSWSManCombinedTrace, Disable-WSManTrace, Enable-PSTrace...}                                                                                                                 
Binary     1.1.0.0    PSScheduledJob                      {New-JobTrigger, Add-JobTrigger, Remove-JobTrigger, Get-JobTrigger...}                                                                                                                                 
Manifest   2.0.0.0    PSWorkflow                          {New-PSWorkflowExecutionOption, New-PSWorkflowSession, nwsn}                                                                                                                                           
Manifest   1.0.0.0    PSWorkflowUtility                   Invoke-AsWorkflow                                                                                                                                                                                      
Manifest   2.0.0.0    RemoteDesktop                       {Get-RDCertificate, Set-RDCertificate, New-RDCertificate, New-RDVirtualDesktopDeployment...}                                                                                                           
Manifest   1.0.0.0    ScheduledTasks                      {Get-ScheduledTask, Set-ScheduledTask, Register-ScheduledTask, Unregister-ScheduledTask...}                                                                                                            
Manifest   2.0.0.0    SecureBoot                          {Confirm-SecureBootUEFI, Set-SecureBootUEFI, Get-SecureBootUEFI, Format-SecureBootUEFI...}                                                                                                             
Manifest   1.0.0.0    SecurityCmdlets                     {Backup-SecurityPolicy, Restore-SecurityPolicy, Backup-AuditPolicy, Restore-AuditPolicy}                                                                                                               
Script     1.0.0.0    ServerCore                          {Get-DisplayResolution, Set-DisplayResolution}                                                                                                                                                         
Script     2.0.0.0    ServerManager                       {Get-WindowsFeature, Install-WindowsFeature, Uninstall-WindowsFeature, Enable-ServerManagerStandardUserRemoting...}                                                                                    
Cim        1.0.0.0    ServerManagerTasks                  {Get-SMCounterSample, Get-SMPerformanceCollector, Start-SMPerformanceCollector, Stop-SMPerformanceCollector...}                                                                                        
Manifest   2.0.0.0    SmbShare                            {Get-SmbShare, Remove-SmbShare, Set-SmbShare, Block-SmbShareAccess...}                                                                                                                                 
Manifest   2.0.0.0    SmbWitness                          {Get-SmbWitnessClient, Move-SmbWitnessClient, gsmbw, msmbw...}                                                                                                                                         
Manifest   2.0.0.0    SoftwareInventoryLogging            {Get-SilComputer, Get-SilComputerIdentity, Get-SilSoftware, Get-SilWindowsUpdate...}                                                                                                                   
Manifest   1.0.0.0    StartLayout                         {Export-StartLayout, Import-StartLayout, Export-StartLayoutEdgeAssets, Get-StartApps}                                                                                                                  
Manifest   2.0.0.0    Storage                             {Add-InitiatorIdToMaskingSet, Add-PartitionAccessPath, Add-PhysicalDisk, Add-StorageFaultDomain...}                                                                                                    
Manifest   1.0.0.0    StorageBusCache                     {Clear-StorageBusDisk, Disable-StorageBusCache, Disable-StorageBusDisk, Enable-StorageBusCache...}                                                                                                     
Manifest   2.0.0.0    TLS                                 {New-TlsSessionTicketKey, Enable-TlsSessionTicketKey, Disable-TlsSessionTicketKey, Export-TlsSessionTicketKey...}                                                                                      
Manifest   1.0.0.0    TroubleshootingPack                 {Get-TroubleshootingPack, Invoke-TroubleshootingPack}                                                                                                                                                  
Manifest   2.0.0.0    TrustedPlatformModule               {Get-Tpm, Initialize-Tpm, Clear-Tpm, Unblock-Tpm...}                                                                                                                                                   
Binary     2.1.639.0  UEV                                 {Clear-UevConfiguration, Clear-UevAppxPackage, Restore-UevBackup, Set-UevTemplateProfile...}                                                                                                           
Manifest   1.0.0.0    UserAccessLogging                   {Enable-Ual, Disable-Ual, Get-Ual, Get-UalDns...}                                                                                                                                                      
Manifest   2.0.0.0    VpnClient                           {Add-VpnConnection, Set-VpnConnection, Remove-VpnConnection, Get-VpnConnection...}                                                                                                                     
Manifest   1.0.0.0    Wdac                                {Get-OdbcDriver, Set-OdbcDriver, Get-OdbcDsn, Add-OdbcDsn...}                                                                                                                                          
Manifest   2.0.0.0    Whea                                {Get-WheaMemoryPolicy, Set-WheaMemoryPolicy}                                                                                                                                                           
Manifest   1.0.0.0    WindowsDeveloperLicense             {Get-WindowsDeveloperLicense, Unregister-WindowsDeveloperLicense, Show-WindowsDeveloperLicenseRegistration}                                                                                            
Script     1.0        WindowsErrorReporting               {Enable-WindowsErrorReporting, Disable-WindowsErrorReporting, Get-WindowsErrorReporting}                                                                                                               
Manifest   1.0.0.0    WindowsSearch                       {Get-WindowsSearchSetting, Set-WindowsSearchSetting}                                                                                                                                                   
Manifest   1.0.0.0    WindowsUpdate                       Get-WindowsUpdateLog                                                                                                                                                                                   
Manifest   1.0.0.2    WindowsUpdateProvider               {Get-WUAVersion, Get-WULastInstallationDate, Get-WULastScanSuccessDate, Get-WUIsPendingReboot...}                                                                                                      

    Directory: C:\Program Files (x86)\Microsoft SQL Server\140\Tools\PowerShell\Modules

ModuleType Version    Name                                ExportedCommands                                                                                                                                                                                       
---------- -------    ----                                ----------------                                                                                                                                                                                       
Manifest   14.0       SQLPS                               {Backup-SqlDatabase, Save-SqlMigrationReport, Add-SqlAvailabilityDatabase, Add-SqlAvailabilityGroupListenerStaticIp...}     

Debug output

key:
{Sanitized from this output}
sasToken:
{Sanitized from this output}
accountId:
{Sanitized from this output}
DEBUG: Sought all Az modules and got latest version 0.0.0
DEBUG: 11:38:56 PM - ConnectAzureRmAccountCommand begin processing with ParameterSet 'AccessTokenWithSubscriptionId'.
DEBUG: 11:38:56 PM - Autosave setting from startup session: 'CurrentUser'
DEBUG: 11:38:56 PM - No autosave setting detected in environment variable 'AzContextAutoSave'. 
DEBUG: 11:38:56 PM - Using Autosave scope 'CurrentUser'
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

Absolute Uri:
https://management.azure.com/tenants?api-version=2016-06-01

Headers:
x-ms-client-request-id        : edeeac07-c961-40f5-89b4-e80271dc9cfa
accept-language               : en-US

Body:

DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
Unauthorized

Headers:
Pragma                        : no-cache
x-ms-failure-cause            : gateway
x-ms-request-id               : 025cf74e-2159-4a7a-9c32-1cde6f4bc0c2
x-ms-correlation-request-id   : 025cf74e-2159-4a7a-9c32-1cde6f4bc0c2
x-ms-routing-request-id       : WESTUS2:20200730T233856Z:025cf74e-2159-4a7a-9c32-1cde6f4bc0c2
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
Connection                    : close
Cache-Control                 : no-cache
Date                          : Thu, 30 Jul 2020 23:38:56 GMT
WWW-Authenticate              : Bearer authorization_uri="https://login.windows.net/", error="invalid_token", error_description="The access token is invalid."

Body:
{
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "The access token is invalid."
  }
}

Connect-AzAccount : The access token is invalid.
At C:\dev\OptiRTCAzure\AppveyorBuildScripts\ConnectAzAccountFails.ps1:24 char:1
+ Connect-AzAccount -AccessToken $sasToken -AccountId $accountId
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Connect-AzAccount], CloudException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand

DEBUG: AzureQoSEvent: CommandName - Connect-AzAccount; IsSuccess - False; Duration - 00:00:00.7427651;; Exception - Microsoft.Rest.Azure.CloudException: The access token is invalid.
   at Microsoft.Azure.Internal.Subscriptions.TenantsOperations.<ListWithHttpMessagesAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Azure.Internal.Subscriptions.TenantsOperationsExtensions.<ListAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Azure.Internal.Subscriptions.TenantsOperationsExtensions.List(ITenantsOperations operations)
   at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.ListAccountTenants(IAzureAccount account, IAzureEnvironment environment, SecureString password, String promptBehavior, Action`1 promptAction)
   at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.Login(IAzureAccount account, IAzureEnvironment environment, String tenantId, String subscriptionId, String subscriptionName, SecureString password, Boolean skipValidation, Action`1 promptA
ction, String name, Boolean shouldPopulateContextList)
   at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayClass92_0.<ExecuteCmdlet>b__0(AzureRmProfile localProfile, RMProfileClient profileClient, String name)
   at Microsoft.Azure.Commands.Profile.Common.AzureContextModificationCmdlet.ModifyContext(Action`2 contextAction)
   at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.SetContextWithOverwritePrompt(Action`3 setContextAction)
   at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.ExecuteCmdlet()
   at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord();
DEBUG: Finish sending metric.
DEBUG: 11:38:58 PM - ConnectAzureRmAccountCommand end processing.

Error output

Resolve-AzError
DEBUG: 11:41:46 PM - ResolveError begin processing with ParameterSet 'AnyErrorParameterSet'.
WARNING: Breaking changes in the cmdlet 'Resolve-AzError' :
WARNING:  - The `Resolve-Error` alias will be removed in a future release.  Please change any scripts that use this alias to use `Resolve-AzError` instead.

WARNING: NOTE : Go to https://aka.ms/azps-changewarnings for steps to suppress this breaking change warning, and other information on breaking changes in Azure PowerShell.

   HistoryId: 8

RequestId      : 025cf74e-2159-4a7a-9c32-1cde6f4bc0c2
Message        : The access token is invalid.
ServerMessage  : InvalidAuthenticationToken: The access token is invalid. (System.Collections.Generic.List`1[Microsoft.Rest.Azure.CloudError])
ServerResponse : {Unauthorized}
RequestMessage : {GET https://management.azure.com/tenants?api-version=2016-06-01}
InvocationInfo : {Connect-AzAccount}
Line           : Connect-AzAccount -AccessToken $sasToken -AccountId $accountId

Position       : At C:\dev\OptiRTCAzure\AppveyorBuildScripts\ConnectAzAccountFails.ps1:24 char:1
                 + Connect-AzAccount -AccessToken $sasToken -AccountId $accountId
                 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
StackTrace     :    at Microsoft.Azure.Internal.Subscriptions.TenantsOperations.<ListWithHttpMessagesAsync>d__5.MoveNext()
                 --- End of stack trace from previous location where exception was thrown ---
                    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                    at Microsoft.Azure.Internal.Subscriptions.TenantsOperationsExtensions.<ListAsync>d__1.MoveNext()
                 --- End of stack trace from previous location where exception was thrown ---
                    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                    at Microsoft.Azure.Internal.Subscriptions.TenantsOperationsExtensions.List(ITenantsOperations operations)
                    at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.ListAccountTenants(IAzureAccount account, IAzureEnvironment environment, SecureString password, String promptBehavior, Action`1 promptAction)
                    at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.Login(IAzureAccount account, IAzureEnvironment environment, String tenantId, String subscriptionId, String subscriptionName, SecureString password, Boolean 
                 skipValidation, Action`1 promptAction, String name, Boolean shouldPopulateContextList)
                    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayClass92_0.<ExecuteCmdlet>b__0(AzureRmProfile localProfile, RMProfileClient profileClient, String name)
                    at Microsoft.Azure.Commands.Profile.Common.AzureContextModificationCmdlet.ModifyContext(Action`2 contextAction)
                    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.SetContextWithOverwritePrompt(Action`3 setContextAction)
                    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.ExecuteCmdlet()
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
HistoryId      : 8

The Azure PowerShell team is listening, please let us know how we are doing: https://aka.ms/azpssurvey?Q_CHL=ERROR.

DEBUG: AzureQoSEvent: CommandName - Resolve-AzError; IsSuccess - True; Duration - 00:00:00.1404737;
DEBUG: Finish sending metric.
DEBUG: 11:41:47 PM - ResolveError end processing.
dingmeng-xue commented 4 years ago

I'm not sure token can be generated locally. Could you share your token to us? Ensure token is expired before sharing to us. Another approach is you can try Invoke-RestMethod to verify your token.

Paqi commented 4 years ago

@dingmeng-xue Yes, SAS Tokens can be generated locally. Searching for "Azure Generate SAS Token" will yield several examples.

Here is an expired token I generated using the example script I shared in my post above:

SharedAccessSignature uid=integration&ex=2020-07-31T13:12:52.4713452Z&sn=J5P39xggTT3KYo0TrZeqa74xmHtQbR0LCDU6BQhEsdMtZHioJD0vJY3ZF74aZTxLsZ2w6mekw64+HiZ79xPVlw==

Like I said in that post, I have already verified these tokens are valid by executing a REST request to our APIM tenant. I verified this SAS token I'm sharing worked for that request as well.

dingmeng-xue commented 4 years ago

SAS token is for storage but it is not for connecting Azure. Access token of Azure PowerShell is used for Azure AD.

Paqi commented 4 years ago

@dingmeng-xue I don't understand, can you elaborate? I've seen usages of SAS tokens to access things other than storage. For example, the Azure API Management REST API uses SAS tokens to authenticate requests: https://docs.microsoft.com/en-us/rest/api/apimanagement/apimanagementrest/api-management-rest#Authentication

Here is the parameter set I'm using for Connect-AzAccount:

Connect-AzAccount
       [-Environment <String>]
       [-Tenant <String>]
       -AccessToken <String>
       [-GraphAccessToken <String>]
       [-KeyVaultAccessToken <String>]
       -AccountId <String>
       [-Subscription <String>]
       [-ContextName <String>]
       [-SkipValidation]
       [-SkipContextPopulation]
       [-Force]
       [-Scope <ContextModificationScope>]
       [-DefaultProfile <IAzureContextContainer>]
       [-WhatIf]
       [-Confirm]
       [<CommonParameters>]

Source: https://docs.microsoft.com/en-us/powershell/module/az.accounts/connect-azaccount?view=azps-4.4.0

What does this parameter set expect to be passed into the AccessToken parameter? Something other than a SAS Token?

Paqi commented 4 years ago

Here's some additional context that may be helpful:

I have a script that is run by an automated build process. That script needs to use the following cmdlets:

Before I can use those cmdlets, I need to use Connect-AzAccount. Because this script is run by an automated process, we can't use an interactive interface to provide Azure AD credentials. That's why I need to know what to pass into the AccessToken parameter. The documentation I have read has lead me to believe this should be a SAS Token, but if I should be using something else, please let me know what kind of token is expected by Connect-AzAccount

dingmeng-xue commented 4 years ago

@rabrahamOpti , token contains audience and scope information. Since SAS token and ARM token used by Azure PowerShell are different, you cannot use SAS token to access Azure resource management endpoints.

For your case, the correct way is to create service principal or managed identity and then Connect-AzAccount using that account in automation environment. Please search azure service principal and there are many docs around it.

Paqi commented 4 years ago

Hi @dingmeng-xue

I just rechecked the documentation for Connect-AzAccount. Connecting to a service principal account seems to use a different parameter set than the parameter set that uses AccessToken.

Could you please tell me what type of token should be passed into the AccessToken parameter?

Here is the documentation for connecting to the service principal account. Note that it does not include the AccessToken parameter:

Example 3: Connect to Azure using a service principal account

The first command prompts for service principal credentials and stores them in the $Credential variable. Enter your application ID for the username and service principal secret as the password when prompted. The second command connects the specified Azure tenant using the service principal credentials stored in the $Credential variable. The ServicePrincipal switch parameter indicates that the account authenticates as a service principal.

$Credential = Get-Credential
Connect-AzAccount -Credential $Credential -Tenant 'xxxx-xxxx-xxxx-xxxx' -ServicePrincipal

Account                SubscriptionName TenantId                Environment
-------                ---------------- --------                -----------
xxxx-xxxx-xxxx-xxxx    Subscription1    xxxx-xxxx-xxxx-xxxx     AzureCloud

Edit

This would be the way to do it in an automated process. It also does not use AccessToken

Example 7: Connect using certificates

This example connects to an Azure account using certificate-based service principal authentication. The service principal used for authentication must be created with the specified certificate. For more information on creating a self-signed certificates and assigning them permissions, see Use Azure PowerShell to create a service principal with a certificate

$Thumbprint = '0SZTNJ34TCCMUJ5MJZGR8XQD3S0RVHJBA33Z8ZXV'
$TenantId = '4cd76576-b611-43d0-8f2b-adcb139531bf'
$ApplicationId = '3794a65a-e4e4-493d-ac1d-f04308d712dd'
Connect-AzAccount -CertificateThumbprint $Thumbprint -ApplicationId $ApplicationId -Tenant $TenantId -ServicePrincipal

Account             SubscriptionName TenantId            Environment
-------             ---------------- --------            -----------
xxxx-xxxx-xxxx-xxxx Subscription1    xxxx-xxxx-xxxx-xxxx AzureCloud

Account          : 3794a65a-e4e4-493d-ac1d-f04308d712dd
SubscriptionName : MyTestSubscription
SubscriptionId   : 85f0f653-1f86-4d2c-a9f1-042efc00085c
TenantId         : 4cd76576-b611-43d0-8f2b-adcb139531bf
Environment      : AzureCloud
Paqi commented 4 years ago

Can you please point me to an example of using the following parameter set?

Connect-AzAccount
       [-Environment <String>]
       [-Tenant <String>]
       -AccessToken <String>
       [-GraphAccessToken <String>]
       [-KeyVaultAccessToken <String>]
       -AccountId <String>
       [-Subscription <String>]
       [-ContextName <String>]
       [-SkipValidation]
       [-SkipContextPopulation]
       [-MaxContextPopulation <Int32>]
       [-Force]
       [-Scope <ContextModificationScope>]
       [-DefaultProfile <IAzureContextContainer>]
       [-WhatIf]
       [-Confirm]
       [<CommonParameters>]
dingmeng-xue commented 4 years ago

@rabrahamOpti , here is a doc for app and service principal creation. Then you can add secret to that app. Once you follow the steps, you can use below example. Credential is the combination of app id and secret. Certificate is a similar way and you need to create certificate with private key for it.

Connect-AzAccount -Credential $Credential -Tenant 'xxxx-xxxx-xxxx-xxxx' -ServicePrincipal

AccessToken is normally used by Cloud Solution Providers because they can get an accesstoken via PartnerCenter and then access resources owned by their customers. If you are not CSP, one way you can try accesstoken is to copy token from Fiddler recording or Chrome Debugger Tools. But it's not correct way for normal job.

Paqi commented 4 years ago

@dingmeng-xue could you describe for me what to look for in the chrome debugger to see what this token looks like? I'd like to look

dingmeng-xue commented 4 years ago

Actually, it's out of our scope. Information can be found on internet. Below 2 are for your reference

https://developers.google.com/web/tools/chrome-devtools/network/reference http://www.infinitepartitions.com/cgi-bin/showarticle.cgi?article=art034

dingmeng-xue commented 4 years ago

I'm closing this issue now.

Paqi commented 4 years ago

@dingmeng-xue I know how to use the chrome debugger. Can you tell me what header to look for? I want to see what the format of that token is

dingmeng-xue commented 4 years ago

It should be authorization: Bearer ..... on request header.

Another approach is you can leverage Azure CLI. Once you az login, you can get access token by az account get-access-token

Paqi commented 4 years ago

Got it. Great, thank you for your help!