Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

azcontext.TokenCache is null with Az.Accounts > v1.9.5 and breaks Azure Login scenarios #13337

Closed
cschertzmsft opened this issue Oct 27, 2020 · 19 comments
Assignees
Labels
Authentication feature-request This issue requires a new behavior in the product in order be resolved. P1

Comments

@cschertzmsft
Copy link

cschertzmsft commented Oct 27, 2020

Description

azcontext.TokenCache is null when using Az.Accounts > v1.9.5. When someone installs Az PowerShell since 10/27, login scenarios appear to be broken. Downgrading Az.Accounts to 1.9.5 seems to work but is a major issue with Partners who we have install Az PowerShell and asking them to delete Az.Accounts (say v2.1.0) and reinstall v1.9.5.

Steps to reproduce

Connect-AzAccount -Tenant 72f988bf-86f1-41af-91ab-2d7cd011db49
WARNING: TenantId '72f988bf-86f1-41af-91ab-2d7cd011db49' contains more than one active subscription. First one will be
selected for further use. To select another subscription, use Set-AzContext.

Account                SubscriptionName                TenantId                             Environment
-------                ----------------                --------                             -----------
foo@micro.com MCVP MSAAD - Product - ENG01 US 72f988bf-86f1-41af-91ab-2d7cd011db49 AzureCloud


PS C:\WINDOWS\system32> $context = Get-AzContext
PS C:\WINDOWS\system32> $context

Name                                     Account             SubscriptionName    Environment         TenantId
----                                     -------             ----------------    -----------         --------
FOOBAR - Product - ENG01 US (ed62... foo@micro... MCVP MSAAD - Pro... AzureCloud          72f988bf-86f1-4...


PS C:\WINDOWS\system32> $context.Tenant

Id                                   Name Category Domains
--                                   ---- -------- -------
72f988bf-86f1-41af-91ab-2d7cd011db49


PS C:\WINDOWS\system32> $context.TokenCache
PS C:\WINDOWS\system32> $context.TokenCache.ReadItems()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $context.TokenCache.ReadItems()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Environment data

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

Module versions

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.10.0.0   7Zip4Powershell                     {Expand-7Zip, Compress-7Zip, Get-7Zip, Get-7ZipInformation}
Script     2.1.0      Az.Accounts                         {Disable-AzDataCollection, Disable-AzContextAutosave, Enab...
Script     1.1.1      Az.Advisor                          {Get-AzAdvisorRecommendation, Enable-AzAdvisorRecommendati...
Script     1.3.0      Az.Aks                              {Get-AzAksCluster, New-AzAksCluster, Remove-AzAksCluster, ...
Script     1.1.4      Az.AnalysisServices                 {Resume-AzAnalysisServicesServer, Suspend-AzAnalysisServic...
Script     2.1.0      Az.ApiManagement                    {Add-AzApiManagementApiToGateway, Add-AzApiManagementApiTo...
Script     1.1.0      Az.ApplicationInsights              {Get-AzApplicationInsights, New-AzApplicationInsights, Rem...
Script     1.4.0      Az.Automation                       {Get-AzAutomationHybridWorkerGroup, Remove-AzAutomationHyb...
Script     3.1.0      Az.Batch                            {Remove-AzBatchAccount, Get-AzBatchAccount, Get-AzBatchAcc...
Script     1.0.3      Az.Billing                          {Get-AzBillingInvoice, Get-AzBillingPeriod, Get-AzEnrollme...
Script     1.4.3      Az.Cdn                              {Get-AzCdnProfile, Get-AzCdnProfileSsoUrl, New-AzCdnProfil...
Script     1.7.0      Az.CognitiveServices                {Get-AzCognitiveServicesAccount, Get-AzCognitiveServicesAc...
Script     4.5.0      Az.Compute                          {Remove-AzAvailabilitySet, Get-AzAvailabilitySet, New-AzAv...
Script     1.0.3      Az.ContainerInstance                {New-AzContainerGroup, Get-AzContainerGroup, Remove-AzCont...
Script     1.1.1      Az.ContainerRegistry                {New-AzContainerRegistry, Get-AzContainerRegistry, Update-...
Script     1.1.0      Az.DataBoxEdge                      {Get-AzDataBoxEdgeJob, Get-AzDataBoxEdgeDevice, Invoke-AzD...
Script     1.0.0      Az.Databricks                       {Get-AzDatabricksVNetPeering, Get-AzDatabricksWorkspace, N...
Script     1.10.2     Az.DataFactory                      {Set-AzDataFactoryV2, Update-AzDataFactoryV2, Get-AzDataFa...
Script     1.0.2      Az.DataLakeAnalytics                {Get-AzDataLakeAnalyticsDataSource, New-AzDataLakeAnalytic...
Script     1.2.8      Az.DataLakeStore                    {Get-AzDataLakeStoreTrustedIdProvider, Remove-AzDataLakeSt...
Script     1.0.0      Az.DataShare                        {New-AzDataShareAccount, Get-AzDataShareAccount, Remove-Az...
Script     1.1.0      Az.DeploymentManager                {Get-AzDeploymentManagerArtifactSource, New-AzDeploymentMa...
Script     1.0.0      Az.DesktopVirtualization            {Disconnect-AzWvdUserSession, Get-AzWvdApplication, Get-Az...
Script     1.0.2      Az.DevTestLabs                      {Get-AzDtlAllowedVMSizesPolicy, Get-AzDtlAutoShutdownPolic...
Script     1.1.2      Az.Dns                              {Get-AzDnsRecordSet, New-AzDnsRecordConfig, Remove-AzDnsRe...
Script     1.3.0      Az.EventGrid                        {New-AzEventGridTopic, Get-AzEventGridTopic, Set-AzEventGr...
Script     1.7.0      Az.EventHub                         {New-AzEventHubNamespace, Get-AzEventHubNamespace, Set-AzE...
Script     1.6.1      Az.FrontDoor                        {New-AzFrontDoor, Get-AzFrontDoor, Set-AzFrontDoor, Remove...
Script     1.0.2      Az.Functions                        {Get-AzFunctionApp, Get-AzFunctionAppAvailableLocation, Ge...
Script     3.6.1      Az.HDInsight                        {Get-AzHDInsightJob, New-AzHDInsightSqoopJobDefinition, Wa...
Script     1.1.0      Az.HealthcareApis                   {New-AzHealthcareApisService, Remove-AzHealthcareApisServi...
Script     2.6.0      Az.IotHub                           {Add-AzIotHubKey, Get-AzIotHubEventHubConsumerGroup, Get-A...
Script     2.2.1      Az.KeyVault                         {Add-AzKeyVaultCertificate, Update-AzKeyVaultCertificate, ...
Script     1.0.0      Az.Kusto                            {Add-AzKustoClusterLanguageExtension, Add-AzKustoDatabaseP...
Script     1.3.2      Az.LogicApp                         {Get-AzIntegrationAccountAgreement, Get-AzIntegrationAccou...
Script     1.1.3      Az.MachineLearning                  {Move-AzMlCommitmentAssociation, Get-AzMlCommitmentAssocia...
Script     1.1.0      Az.Maintenance                      {Get-AzApplyUpdate, Get-AzConfigurationAssignment, Get-AzM...
Script     1.1.1      Az.ManagedServices                  {Get-AzManagedServicesAssignment, New-AzManagedServicesAss...
Script     1.0.2      Az.MarketplaceOrdering              {Get-AzMarketplaceTerms, Set-AzMarketplaceTerms}
Script     1.1.1      Az.Media                            {Sync-AzMediaServiceStorageKey, Set-AzMediaServiceKey, Get...
Script     2.2.0      Az.Monitor                          {Get-AzMetricDefinition, Get-AzMetric, Remove-AzLogProfile...
Script     3.5.0      Az.Network                          {Add-AzApplicationGatewayAuthenticationCertificate, Get-Az...
Script     1.1.1      Az.NotificationHubs                 {Get-AzNotificationHub, Get-AzNotificationHubAuthorization...
Script     2.3.0      Az.OperationalInsights              {New-AzOperationalInsightsAzureActivityLogDataSource, New-...
Script     1.3.1      Az.PolicyInsights                   {Get-AzPolicyEvent, Get-AzPolicyState, Get-AzPolicyStateSu...
Script     1.1.2      Az.PowerBIEmbedded                  {Remove-AzPowerBIWorkspaceCollection, Get-AzPowerBIWorkspa...
Script     1.0.3      Az.PrivateDns                       {Get-AzPrivateDnsZone, Remove-AzPrivateDnsZone, Set-AzPriv...
Script     2.12.2     Az.RecoveryServices                 {Get-AzRecoveryServicesBackupProperty, Get-AzRecoveryServi...
Script     1.4.0      Az.RedisCache                       {Remove-AzRedisCachePatchSchedule, New-AzRedisCacheSchedul...
Script     1.0.3      Az.Relay                            {New-AzRelayNamespace, Get-AzRelayNamespace, Set-AzRelayNa...
Script     2.5.1      Az.Resources                        {Get-AzProviderOperation, Remove-AzRoleAssignment, Get-AzR...
Script     1.4.1      Az.ServiceBus                       {New-AzServiceBusNamespace, Get-AzServiceBusNamespace, Set...
Script     2.2.0      Az.ServiceFabric                    {Add-AzServiceFabricClientCertificate, Add-AzServiceFabric...
Script     1.2.0      Az.SignalR                          {New-AzSignalR, Get-AzSignalR, Get-AzSignalRKey, New-AzSig...
Script     2.11.0     Az.Sql                              {Get-AzSqlDatabaseTransparentDataEncryption, Get-AzSqlData...
Script     1.1.0      Az.SqlVirtualMachine                {New-AzSqlVM, Get-AzSqlVM, Update-AzSqlVM, Remove-AzSqlVM...}
Script     2.7.0      Az.Storage                          {Get-AzStorageAccount, Get-AzStorageAccountKey, New-AzStor...
Script     1.3.0      Az.StorageSync                      {Invoke-AzStorageSyncCompatibilityCheck, New-AzStorageSync...
Script     1.0.1      Az.StreamAnalytics                  {Get-AzStreamAnalyticsFunction, Get-AzStreamAnalyticsDefau...
Script     1.0.0      Az.Support                          {Get-AzSupportService, Get-AzSupportProblemClassification,...
Script     1.0.4      Az.TrafficManager                   {Add-AzTrafficManagerCustomHeaderToEndpoint, Remove-AzTraf...
Script     1.11.0     Az.Websites                         {Get-AzAppServicePlan, Set-AzAppServicePlan, New-AzAppServ...
Script     5.1.2      Azure                               {Get-AzureAutomationCertificate, Get-AzureAutomationConnec...
Binary     2.0.2.104  AzureAD                             {Add-AzureADApplicationOwner, Get-AzureADApplication, Get-...
Binary     2.0.2.76   AzureAD                             {Add-AzureADApplicationOwner, Get-AzureADApplication, Get-...
Script     1.0.0.8    DockerMsftProvider
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-Packa...
Script     3.4.0      Pester                              {Describe, Context, It, Should...}
Script     0.14.0     platyPS                             {New-MarkdownHelp, Get-MarkdownMetadata, New-ExternalHelp,...
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...
Script     1.0.0.0    AssignedAccess                      {Clear-AssignedAccess, Get-AssignedAccess, Set-AssignedAcc...
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        ConfigDefender                      {Get-MpPreference, Set-MpPreference, Add-MpPreference, Rem...
Manifest   1.0        Defender                            {Get-MpPreference, Set-MpPreference, Add-MpPreference, Rem...
Manifest   1.0.2.0    DeliveryOptimization                {Delete-DeliveryOptimizationCache, Set-DeliveryOptimizatio...
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   1.0.0.0    HgsClient                           {Get-HgsAttestationBaselinePolicy, Get-HgsClientConfigurat...
Manifest   1.0.0.0    HgsDiagnostics                      {New-HgsTraceTarget, Get-HgsTrace, Get-HgsTraceFileData, T...
Binary     1.0.0.0    HostComputeService                  {Get-ComputeProcess, Stop-ComputeProcess}
Manifest   1.0.0.1    HostNetworkingService               {Remove-HnsNamespace, Remove-HnsEndpoint, Get-HnsEndpoint,...
Binary     2.0.0.0    Hyper-V                             {Add-VMAssignableDevice, Add-VMDvdDrive, Add-VMFibreChanne...
Binary     1.1        Hyper-V                             {Add-VMDvdDrive, Add-VMFibreChannelHba, Add-VMHardDiskDriv...
Manifest   2.0.0.0    International                       {Get-WinDefaultInputMethodOverride, Set-WinDefaultInputMet...
Manifest   1.0.0.0    iSCSI                               {Get-IscsiTargetPortal, New-IscsiTargetPortal, Remove-Iscs...
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    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.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    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...
Script     3.0        Provisioning                        {Install-ProvisioningPackage, Export-ProvisioningPackage, ...
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   1.0.0.0    ScheduledTasks                      {Get-ScheduledTask, Set-ScheduledTask, Register-ScheduledT...
Manifest   2.0.0.0    SecureBoot                          {Confirm-SecureBootUEFI, Set-SecureBootUEFI, Get-SecureBoo...
Manifest   3.1.0.0    ServiceFabric                       {Get-ServiceFabricServiceName, Get-ServiceFabricApplicatio...
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   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   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


Error output


@adriansali
Copy link
Member

The issues seems to be in the new version of Az.Accounts - 2.1.0. Downgrading to 1.9.5 fixes the issue. On the other hand, it also doesn't work in PS 7 with Az.Accounts 2.1.0. So the version of PS does not seem relevant.

@jpwarner67
Copy link

Although there is a work-around (for now) to delete Az.Accounts > 1.9.5 (and reinstall 1.9.5), it will be painful to deal with an incoming stream of support issues from folks who will be broken (with a basic login scenario) and told to use the work-around.

Possible to have someone look at this as soon as possible since it impacts azure login?

Thanks!

@jpwarner67 jpwarner67 changed the title azcontext.TokenCache is null when running is PS 5.1 run Az 4.8 and 5.0 azcontext.TokenCache is null with AzAccounts > v1.9.5 Oct 27, 2020
@jpwarner67 jpwarner67 changed the title azcontext.TokenCache is null with AzAccounts > v1.9.5 azcontext.TokenCache is null with Az.Accounts > v1.9.5 Oct 27, 2020
@dineshreddy007
Copy link
Contributor

We are using TokenCache.ReadItems() after Connect-AZAccount to read token cache, which is working fine in version1.9.5.

From 2.1.0, reading from token cache fails with below error.

[Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureTokenCache] does not contain a method named 'ReadItems'

In our case, we use it to register on-premises Azure Stack HCI
to Azure. Though downgrading to 1.9.5 workaround fixes the issue, it would be hard to communicate this to customers and handle the support requests. Can someone please look into this as soon as possible.

@jpwarner67 jpwarner67 changed the title azcontext.TokenCache is null with Az.Accounts > v1.9.5 azcontext.TokenCache is null with Az.Accounts > v1.9.5 and breaks Azure Login scenarios Oct 27, 2020
@dingmeng-xue dingmeng-xue added Authentication feature-request This issue requires a new behavior in the product in order be resolved. and removed triage labels Oct 28, 2020
@erich-wang
Copy link
Member

Thanks for reporting the issue. Since Az.Accounts 2.x, the authentication library is changed from ADAL to MSAL, MSAL library and extension is responsible for token cache encryption. We don't expose token cache object because of security concern. However, we also realize that get access token is valid scenario, we plan to add one additional cmdlet Get-AzAccessToken to serve such purpose, and plan to release it in next sprint.

@erich-wang erich-wang self-assigned this Oct 28, 2020
@cschertzmsft
Copy link
Author

Great to hear that finally that Get-AzAccessToken will exist. Wondering if there are details on what it will support.

Also it is nice that this is coming but the current release breaks all existing usage of the TokenCache back to Az 4.3 which is going to cause a bunch of nasty support issues. Also dont see any release notice to 2.1 with any breaking change notifications. Not sure how to deal with a well documented workaround for the missing Get-AzAccessToken being broken without providing a replacement solution.

@dineshreddy007
Copy link
Contributor

In our case the work around of using 1.9.5 is not working. We use both Az.Resources and Az.Accounts modules. Az.Resources module(even the older version) seems to be installing and using the latest version of Az.Accounts module by default and version 2.1.0 of Az.Accounts is being picked up in PS Session. Can you suggest a workaround that works with using this along with Az.Resources module?

@dingmeng-xue dingmeng-xue added this to the Backlog milestone Oct 29, 2020
@ramirezalfredo
Copy link

ramirezalfredo commented Nov 2, 2020

Tried to downgrade to Az.StackHCI 0.2.0 instead of 0.3.0 and surprise! It gets the latest Az.Accounts 2.1.0. I've been trying to evaluate Azure Stack HCI and no luck at the latest step:

PS C:\Windows\system32> Register-AzStackHCI  `
>>     -SubscriptionId "my-subscription-id" `
>>     -ResourceName "azshciclus" `
>>     -ResourceGroupName "AzureStackHCIRegistration" `
>>     -Region "EastUS" `
>>     -ComputerName "AZSHCINODE01.azshci.local" `
>>     -Credential $azshciNodeCreds
Method invocation failed because [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureTokenCache] does
not contain a method named 'ReadItems'.
At C:\Program Files\WindowsPowerShell\Modules\Az.StackHCI\0.3.0\Az.StackHCI.psm1:200 char:5
+     $graphTokenItem = [Microsoft.Azure.Commands.Common.Authentication ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MethodNotFound

And this happens right after you set 4 or 5 VMs and like I said, it's the latest step to see the thing working!

@erich-wang erich-wang modified the milestones: Backlog, S178 (2020-11-17) Nov 2, 2020
@erich-wang
Copy link
Member

@ramirezalfredo , could you please try the following steps to use 0.2.0:

  1. Restart PowerShell
  2. Install and import Az.Accounts 1.9.5
Install-Module Az.Accounts -RequiredVersion 1.9.5 -Repository PSGallery -Force
Import-Module Az.Accounts -RequiredVersion 1.9.5 

@tadomsft
Copy link

tadomsft commented Nov 3, 2020

I was using the (Get-AzContext).TokenCache.ReadItems() to then test the ExpiresOn to determine if the token is now expired and then force the user to log back in. Is there a better way from Get-AzContext to know if we need to sign back in again?

@o-l-a-v
Copy link

o-l-a-v commented Nov 3, 2020

Different way to get token after Connect-AzAccount, even with newest versions of Az.Account.

$AzContext = Get-AzContext
$ArmToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate(
    $AzContext.'Account',
    $AzContext.'Environment',
    $AzContext.'Tenant'.'Id',
    $null,
    [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never,
    $null,
    'https://management.azure.com/'
)

Resources

@JimGBritt
Copy link
Member

In addition to what was mentioned above, this update has not only impacted token cache retrieval in my PowerShell environment but also basic commands such as Get-AzSubscription. I have access to over 70 subs across 3 tenants and none of them are returned.

Get-AzSubscription

WARNING: Unable to acquire token for tenant '########-####-####-####-###########1'
WARNING: Unable to acquire token for tenant '########-####-####-####-###########2'
WARNING: Unable to acquire token for tenant '########-####-####-####-###########3'

In addition, since we are changing the way we are doing things in 2.x version

"the authentication library is changed from ADAL to MSAL, MSAL library and extension is responsible for token cache encryption"

are we not going to have a deprecation path or is the path to move back? This is going to in fact hit a lot of customers / Azure DevOps pipelines, etc. There is no indication on resolution when this cmdlet us updated and things break.

@JimGBritt
Copy link
Member

In addition to what was mentioned above, this update has not only impacted token cache retrieval in my PowerShell environment but also basic commands such as Get-AzSubscription. I have access to over 70 subs across 3 tenants and none of them are returned.

Get-AzSubscription

WARNING: Unable to acquire token for tenant '########-####-####-####-###########1'
WARNING: Unable to acquire token for tenant '########-####-####-####-###########2'
WARNING: Unable to acquire token for tenant '########-####-####-####-###########3'

In addition, since we are changing the way we are doing things in 2.x version

"the authentication library is changed from ADAL to MSAL, MSAL library and extension is responsible for token cache encryption"

are we not going to have a deprecation path or is the path to move back? This is going to in fact hit a lot of customers / Azure DevOps pipelines, etc. There is no indication on resolution when this cmdlet us updated and things break.

Update here - I had to do a "logout-azAccount" about 3 times (likely for each tenant I was attached to) to clear any cached logins and now the subscription listing returns and also the workaround specified for obtaining a token by @o-l-a-v . I will continue testing this workaround through Azure DevOps, Mac/Linux/Windows to ensure auth is functioning for token access. Will watch this issue for updates.

@o-l-a-v
Copy link

o-l-a-v commented Nov 6, 2020

@JimGBritt

Try "Clear-AzContext -Force" instead next time. Instead of Diconnect-AcAccount, which will not remove all AzContexts in one go.

Try "Get-AzContext -ListAvailable" to see all the tenants/subs you have access to by using "Set-AzContext". Auth with the Az.Accounts module is very different from AzureAD or MsOnline.

@JimGBritt
Copy link
Member

@JimGBritt

Try "Clear-AzContext -Force" instead next time. Instead of Diconnect-AcAccount, which will not remove all AzContexts in one go.

Actually my bad - great point. Thanks for your code example btw. Testing now. Seems to work nicely from PS - will test in other avenues. https://aka.ms/AzPolicyScripts is the source of my current auth woes as I heavily use REST AUTH Tokens - this will help. Need to try backwards compat as well with older cmdlets in Az.Accounts but hoping for good news.

JamesDawson added a commit to corvus-dotnet/Corvus.Deployment that referenced this issue Nov 12, 2020
This is due to changes in the Az.Accounts module where the TokenCache is no longer popoulated.  Ref: Azure/azure-powershell#13337
JamesDawson added a commit to corvus-dotnet/Corvus.Deployment that referenced this issue Nov 13, 2020
Versions of the Az.Accounts module >1.9.5 no longer populate AzContext's TokenCache property, which we relied on when performing Graph API operations. (ref: Azure/azure-powershell#13337)

This change alters the way we test for graph API access and uses the azure-cli `az rest` command to handle authenticating and calling the Graph API.

A future Az PowerShell release may extend the Invoke-AzRestMethod cmdlet to support more endpoints than just AzureRM, which should allow us to switch back to a pure PowerShell solution.
@erich-wang
Copy link
Member

Close the issue as Get-AzAccessToken has been provided in Az.Accounts 2.2 which will be released on Nov 17.

@mgreenegit
Copy link
Member

This issue is still happening as of July 2021

@erich-wang
Copy link
Member

@mgreenegit , azcontext.TokenCache is set as null on purpose after Az.Accounts 2.x because of MSAL migration, user could use Get-AzAccessToken to get token instead. Could you please let us know why do you reopen the issue?

@mgreenegit
Copy link
Member

Ah I see. This issue is similar to what I repro here, but not the same.
#15423

@dzeping96
Copy link

Hi, is there any methods to retrieve RefreshToken? Previously it will store within TokenCache, but it is set as null on purpose now and there is no something similar as Get-AzAccessToken, anybody have a workaround for this? Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Authentication feature-request This issue requires a new behavior in the product in order be resolved. P1
Projects
None yet
Development

No branches or pull requests