Azure / Azure/azure-powershell

Connect-AzAccount Throws Object reference not set to an instance of an object

Open
#9,467 18 comments 0 reactions 1 assignee Claimed by @isra-fel View on GitHub
Azure PS Team Investigate :mag: MSAL
Dominant language
C#
Stars
4.8k
Forks
4.3k
Avg merge
2d 17h
Merged PRs (30d)
51

Description

## Description
I'm writing an application that needs to pull a secret from Azure Key Vault in PowerShell. This application will run on Azure Batch. I'm able to call `Connect-AzAccount` successfully from my dev box, but when I try running it on an Azure VM in Azure Batch, it fails. I'm using certificate authentication and the certificate is exists in both places (I get a different error message if I provide an invalid certificate thumbprint.) I'm not sure what else could be different between the environments

## Steps to reproduce

```powershell
Connect-AzAccount -ServicePrincipal -TenantId $tenantId -CertificateThumbprint $thumbprint -ApplicationId $appId
```

## Environment data

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

## Module versions

```powershell
PS C:\windows\system32> Get-Module -ListAvailable

Directory: C:\Program Files\WindowsPowerShell\Modules

ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 2.0.0 Az.Accounts {Disable-AzDataCollection, Disable-AzContextAutosave, Enab...
Script 1.0.1 Az.Aks {Get-AzAks, New-AzAks, Remove-AzAks, Import-AzAksCredentia...
Script 1.1.0 Az.AnalysisServices {Resume-AzAnalysisServicesServer, Suspend-AzAnalysisServic...
Script 1.1.0 Az.ApiManagement {Add-AzApiManagementApiToProduct, Add-AzApiManagementProdu...
Script 1.0.0 Az.ApplicationInsights {Get-AzApplicationInsights, New-AzApplicationInsights, Rem...
Script 1.2.2 Az.Automation {Get-AzAutomationHybridWorkerGroup, Remove-AzAutomationHyb...
Script 1.1.0 Az.Batch {Remove-AzBatchAccount, Get-AzBatchAccount, Get-AzBatchAcc...
Script 1.0.0 Az.Billing {Get-AzBillingInvoice, Get-AzBillingPeriod, Get-AzEnrollme...
Script 1.3.0 Az.Cdn {Get-AzCdnProfile, Get-AzCdnProfileSsoUrl, New-AzCdnProfil...
Script 1.1.1 Az.CognitiveServices {Get-AzCognitiveServicesAccount, Get-AzCognitiveServicesAc...
Script 2.3.0 Az.Compute {Remove-AzAvailabilitySet, Get-AzAvailabilitySet, New-AzAv...
Script 1.0.1 Az.ContainerInstance {New-AzContainerGroup, Get-AzContainerGroup, Remove-AzCont...
Script 1.0.1 Az.ContainerRegistry {New-AzContainerRegistry, Get-AzContainerRegistry, Update-...
Script 1.1.1 Az.DataFactory {Set-AzDataFactoryV2, Update-AzDataFactoryV2, Get-AzDataFa...
Script 1.0.0 Az.DataLakeAnalytics {Get-AzDataLakeAnalyticsDataSource, New-AzDataLakeAnalytic...
Script 1.2.1 Az.DataLakeStore {Get-AzDataLakeStoreTrustedIdProvider, Remove-AzDataLakeSt...
Script 1.0.0 Az.DeploymentManager {Get-AzDeploymentManagerArtifactSource, New-AzDeploymentMa...
Script 1.0.0 Az.DevTestLabs {Get-AzDtlAllowedVMSizesPolicy, Get-AzDtlAutoShutdownPolic...
Script 1.1.1 Az.Dns {Get-AzDnsRecordSet, New-AzDnsRecordConfig, Remove-AzDnsRe...
Script 1.2.0 Az.EventGrid {New-AzEventGridTopic, Get-AzEventGridTopic, Set-AzEventGr...
Script 1.2.0 Az.EventHub {New-AzEventHubNamespace, Get-AzEventHubNamespace, Set-AzE...
Script 1.1.0 Az.FrontDoor {New-AzFrontDoor, Get-AzFrontDoor, Set-AzFrontDoor, Remove...
Script 2.0.0 Az.HDInsight {Get-AzHDInsightJob, New-AzHDInsightSqoopJobDefinition, Wa...
Script 1.1.0 Az.IotHub {Add-AzIotHubKey, Get-AzIotHubEventHubConsumerGroup, Get-A...
Script 1.2.0 Az.KeyVault {Add-AzKeyVaultCertificate, Update-AzKeyVaultCertificate, ...
Script 1.2.1 Az.LogicApp {Get-AzIntegrationAccountAgreement, Get-AzIntegrationAccou...
Script 1.1.0 Az.MachineLearning {Move-AzMlCommitmentAssociation, Get-AzMlCommitmentAssocia...
Script 1.0.0 Az.MarketplaceOrdering {Get-AzMarketplaceTerms, Set-AzMarketplaceTerms}
Script 1.1.0 Az.Media {Sync-AzMediaServiceStorageKey, Set-AzMediaServiceKey, Get...
Script 1.2.1 Az.Monitor {Get-AzMetricDefinition, Get-AzMetric, Remove-AzLogProfile...
Script 1.10.0 Az.Network {Add-AzApplicationGatewayAuthenticationCertificate, Get-Az...
Script 1.1.0 Az.NotificationHubs {Get-AzNotificationHub, Get-AzNotificationHubAuthorization...
Script 1.3.0 Az.OperationalInsights {New-AzOperationalInsightsAzureActivityLogDataSource, New-...
Script 1.1.1 Az.PolicyInsights {Get-AzPolicyEvent, Get-AzPolicyState, Get-AzPolicyStateSu...
Script 1.1.0 Az.PowerBIEmbedded {Remove-AzPowerBIWorkspaceCollection, Get-AzPowerBIWorkspa...
Script 1.4.1 Az.RecoveryServices {Get-AzRecoveryServicesBackupProperty, Get-AzRecoveryServi...
Script 1.1.0 Az.RedisCache {Remove-AzRedisCachePatchSchedule, New-AzRedisCacheSchedul...
Script 1.0.1 Az.Relay {New-AzRelayNamespace, Get-AzRelayNamespace, Set-AzRelayNa...
Script 1.5.0 Az.Resources {Get-AzProviderOperation, Remove-AzRoleAssignment, Get-AzR...
Script 1.2.0 Az.ServiceBus {New-AzServiceBusNamespace, Get-AzServiceBusNamespace, Set...
Script 1.1.1 Az.ServiceFabric {Add-AzServiceFabricApplicationCertificate, Add-AzServiceF...
Script 1.0.2 Az.SignalR {New-AzSignalR, Get-AzSignalR, Get-AzSignalRKey, New-AzSig...
Script 1.12.0 Az.Sql {Get-AzSqlDatabaseTransparentDataEncryption, Get-AzSqlData...
Script 1.4.0 Az.Storage {Get-AzStorageAccount, Get-AzStorageAccountKey, New-AzStor...
Script 1.0.0 Az.StreamAnalytics {Get-AzStreamAnalyticsFunction, Get-AzStreamAnalyticsDefau...
Script 1.0.1 Az.TrafficManager {Add-AzTrafficManagerCustomHeaderToEndpoint, Remove-AzTraf...
Script 1.3.0 Az.Websites {Get-AzAppServicePlan, Set-AzAppServicePlan, New-AzAppServ...
Script 1.0.1 Microsoft.PowerShell.Operation.V... {Get-OperationValidation, Invoke-OperationValidation}
Script 1.4.2 PackageManagement {Find-Package, Get-Package, Get-PackageProvider, Get-Packa...
Binary 1.0.0.1 PackageManagement {Find-Package, Get-Package, Get-PackageProvider, Get-Packa...
Script 3.4.0 Pester {Describe, Context, It, Should...}
Script 2.1.5 PowerShellGet {Find-Command, Find-DSCResource, Find-Module, Find-RoleCap...
Script 1.0.0.1 PowerShellGet {Install-Module, Find-Module, Save-Module, Update-Module...}
Script 2.0.0 PSReadline {Get-PSReadLineKeyHandler, Set-PSReadLineKeyHandler, Remov...

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

ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 1.0.0.0 AppBackgroundTask {Disable-AppBackgroundTaskDiagnosticLog, Enable-AppBackgro...
Manifest 2.0.0.0 AppLocker {Get-AppLockerFileInformation, Get-AppLockerPolicy, New-Ap...
Manifest 1.0.0.0 AppvClient {Add-AppvClientConnectionGroup, Add-AppvClientPackage, Add...
Manifest 2.0.1.0 Appx {Add-AppxPackage, Get-AppxPackage, Get-AppxPackageManifest...
Manifest 1.0 BestPractices {Get-BpaModel, Get-BpaResult, Invoke-BpaModel, Set-BpaResult}
Manifest 1.0.0.0 BitLocker {Unlock-BitLocker, Suspend-BitLocker, Resume-BitLocker, Re...
Manifest 2.0.0.0 BitsTransfer {Add-BitsFile, Complete-BitsTransfer, Get-BitsTransfer, Re...
Manifest 1.0.0.0 BranchCache {Add-BCDataCacheExtension, Clear-BCCache, Disable-BC, Disa...
Manifest 1.0.0.0 CimCmdlets {Get-CimAssociatedInstance, Get-CimClass, Get-CimInstance,...
Manifest 1.0 ConfigCI {Get-SystemDriver, New-CIPolicyRule, New-CIPolicy, Get-CIP...
Manifest 1.0 Defender {Get-MpPreference, Set-MpPreference, Add-MpPreference, Rem...
Manifest 1.0.1.0 DeliveryOptimization {Get-DeliveryOptimizationStatus, Get-DeliveryOptimizationP...
Binary 2.0.0.0 DFSR {New-DfsReplicationGroup, Get-DfsReplicationGroup, Set-Dfs...
Manifest 1.0.0.0 DirectAccessClientComponents {Disable-DAManualEntryPointSelection, Enable-DAManualEntry...
Script 3.0 Dism {Add-AppxProvisionedPackage, Add-WindowsDriver, Add-Window...
Manifest 1.0.0.0 DnsClient {Resolve-DnsName, Clear-DnsClientCache, Get-DnsClient, Get...
Manifest 1.0.0.0 EventTracingManagement {Start-EtwTraceSession, New-EtwTraceSession, Get-EtwTraceS...
Manifest 2.0.0.0 International {Get-WinDefaultInputMethodOverride, Set-WinDefaultInputMet...
Manifest 1.0.0.0 iSCSI {Get-IscsiTargetPortal, New-IscsiTargetPortal, Remove-Iscs...
Manifest 2.0.0.0 IscsiTarget {Add-ClusteriSCSITargetServerRole, Add-IscsiVirtualDiskTar...
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-KdsC...
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...
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-WSManCredS...
Manifest 1.0 MMAgent {Disable-MMAgent, Enable-MMAgent, Set-MMAgent, Get-MMAgent...
Manifest 1.0.0.0 MsDtc {New-DtcDiagnosticTransaction, Complete-DtcDiagnosticTrans...
Manifest 2.0.0.0 NetAdapter {Disable-NetAdapter, Disable-NetAdapterBinding, Disable-Ne...
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-NetEvent...
Manifest 2.0.0.0 NetLbfo {Add-NetLbfoTeamMember, Add-NetLbfoTeamNic, Get-NetLbfoTea...
Manifest 1.0.0.0 NetNat {Get-NetNat, Get-NetNatExternalAddress, Get-NetNatStaticMa...
Manifest 2.0.0.0 NetQos {Get-NetQosPolicy, Set-NetQosPolicy, Remove-NetQosPolicy, ...
Manifest 2.0.0.0 NetSecurity {Get-DAPolicyChange, New-NetIPsecAuthProposal, New-NetIPse...
Manifest 1.0.0.0 NetSwitchTeam {New-NetSwitchTeam, Remove-NetSwitchTeam, Get-NetSwitchTea...
Manifest 1.0.0.0 NetTCPIP {Get-NetIPAddress, Get-NetIPInterface, Get-NetIPv4Protocol...
Manifest 1.0.0.0 NetworkConnectivityStatus {Get-DAConnectionStatus, Get-NCSIPolicyConfiguration, Rese...
Manifest 1.0.0.0 NetworkSwitchManager {Disable-NetworkSwitchEthernetPort, Enable-NetworkSwitchEt...
Manifest 1.0.0.0 NetworkTransition {Add-NetIPHttpsCertBinding, Disable-NetDnsTransitionConfig...
Manifest 1.0 NFS {Get-NfsMappedIdentity, Get-NfsNetgroup, Install-NfsMappin...
Manifest 1.0.0.0 PcsvDevice {Get-PcsvDevice, Start-PcsvDevice, Stop-PcsvDevice, Restar...
Binary 1.0.0.0 PersistentMemory {Get-PmemDisk, Get-PmemPhysicalDevice, Get-PmemUnusedRegio...
Manifest 1.0.0.0 PKI {Add-CertificateEnrollmentPolicyServer, Export-Certificate...
Manifest 1.0.0.0 PlatformIdentifier Get-PlatformIdentifier
Manifest 1.0.0.0 PnpDevice {Get-PnpDevice, Get-PnpDeviceProperty, Enable-PnpDevice, D...
Manifest 1.1 PrintManagement {Add-Printer, Add-PrinterDriver, Add-PrinterPort, Get-Prin...
Binary 1.0.11 ProcessMitigations {Get-ProcessMitigation, Set-ProcessMitigation, ConvertTo-P...
Manifest 1.1 PSDesiredStateConfiguration {Set-DscLocalConfigurationManager, Start-DscConfiguration,...
Script 1.0.0.0 PSDiagnostics {Disable-PSTrace, Disable-PSWSManCombinedTrace, Disable-WS...
Binary 1.1.0.0 PSScheduledJob {New-JobTrigger, Add-JobTrigger, Remove-JobTrigger, Get-Jo...
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, ...
Manifest 1.0.0.0 ScheduledTasks {Get-ScheduledTask, Set-ScheduledTask, Register-ScheduledT...
Manifest 2.0.0.0 SecureBoot {Confirm-SecureBootUEFI, Set-SecureBootUEFI, Get-SecureBoo...
Manifest 1.0.0.0 SecurityCmdlets {Backup-SecurityPolicy, Restore-SecurityPolicy, Backup-Aud...
Script 1.0.0.0 ServerCore {Get-DisplayResolution, Set-DisplayResolution}
Script 2.0.0.0 ServerManager {Get-WindowsFeature, Install-WindowsFeature, Uninstall-Win...
Cim 1.0.0.0 ServerManagerTasks {Get-SMCounterSample, Get-SMPerformanceCollector, Start-SM...
Manifest 2.0.0.0 SmbShare {Get-SmbShare, Remove-SmbShare, Set-SmbShare, Block-SmbSha...
Manifest 2.0.0.0 SmbWitness {Get-SmbWitnessClient, Move-SmbWitnessClient, gsmbw, msmbw...
Manifest 2.0.0.0 SoftwareInventoryLogging {Get-SilComputer, Get-SilComputerIdentity, Get-SilSoftware...
Manifest 1.0.0.0 StartLayout {Export-StartLayout, Import-StartLayout, Export-StartLayou...
Manifest 2.0.0.0 Storage {Add-InitiatorIdToMaskingSet, Add-PartitionAccessPath, Add...
Manifest 1.0.0.0 StorageBusCache {Clear-StorageBusDisk, Disable-StorageBusCache, Disable-St...
Manifest 2.0.0.0 TLS {New-TlsSessionTicketKey, Enable-TlsSessionTicketKey, Disa...
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-Uev...
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-VpnConnectio...
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-WindowsDeveloperL...
Script 1.0 WindowsErrorReporting {Enable-WindowsErrorReporting, Disable-WindowsErrorReporti...
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-WULastSca...

```

## Debug output

```
PS C:\windows\system32> Connect-AzAccount -ServicePrincipal -TenantId '72f988bf-86f1-41af-91ab-2d7cd011db47' -CertificateThumbprint $thumbprint -ApplicationId $appId
DEBUG: 4:48:52 PM - Autosave setting from startup session: 'CurrentUser'
DEBUG: 4:48:52 PM - No autosave setting detected in environment variable 'AzContextAutoSave'.
DEBUG: 4:48:52 PM - Using Autosave scope 'CurrentUser'
Connect-AzAccount : Object reference not set to an instance of an object.
At line:1 char:1
+ Connect-AzAccount -ServicePrincipal -TenantId '72f988bf-86f1-41af-91a ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Connect-AzAccount], NullReferenceException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand

DEBUG: 4:48:54 PM - ConnectAzureRmAccountCommand end processing.
DEBUG: 4:48:54 PM - ConnectAzureRmAccountCommand end processing.
```

## Error output

```
HistoryId: 12

Message : Object reference not set to an instance of an object.
StackTrace : at Microsoft.Azure.PowerShell.Authenticators.AuthenticationResultToken.get_UserId()
at Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFactory.Authenticate(IAzu
reAccount account, IAzureEnvironment environment, String tenant, SecureString password, String
promptBehavior, Action`1 promptAction, IAzureTokenCache tokenCache, String resourceId)
at Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFactory.Authenticate(IAzu
reAccount account, IAzureEnvironment environment, String tenant, SecureString password, String
promptBehavior, Action`1 promptAction, String resourceId)
at
Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.AcquireAccessToken(IAzureAccount
account, IAzureEnvironment environment, String tenantId, 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, Nullable`1
shouldPopulateContextList)
at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayClass92_0.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()
Exception : System.NullReferenceException
InvocationInfo : {Connect-AzAccount}
Line : Connect-AzAccount -ServicePrincipal -TenantId '72f988bf-86f1-41af-91ab-2d7cd011db47'
-CertificateThumbprint $thumbprint -ApplicationId $appId
Position : At line:1 char:1
+ Connect-AzAccount -ServicePrincipal -TenantId '72f988bf-86f1-41af-91a ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistoryId : 12
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.