Azure / azure-powershell

Microsoft Azure PowerShell
Other
4.22k stars 3.82k forks source link

Missing context in Connect-AzureRMAccount on clean Windows 10 #7131

Open chlillelund opened 6 years ago

chlillelund commented 6 years ago

Description

On a fresh installation of Windows 10, Connect-AzureRMAccount does not return a context. The function runs, but returns the following output.

Account          :  
SubscriptionName :  
SubscriptionId   :  
TenantId         :  
Environment      :

The tenant I am connecting to does not have any Azure subscriptions per se. It is an Office 365 subscription, with a related Azure AD that I need to log in to, in order to create an application, assign permissions, and grant admin consent.

If I from the same clean Windows 10 do a Connect-AzureRMAccount with a user that does have an Azure subscription, a context is created.

Account          :  <user@mydom.dk>
SubscriptionName :  <my subscription>
SubscriptionId   :  <sub id>
TenantId         :  <tenant id>
Environment      :  AzureCloud

After getting this context I can again try with the user that I originally needed to log in with (the Office 365 admin user). And now I get a context

Account          :  <user@office-domain>
SubscriptionName :  <-- empty
SubscriptionId   :  <-- empty
TenantId         :  <tenant id>
Environment      :  AzureCloud

If I then clear all context objects and try again with the Office 365 admin user, I get the following error

> Clear-AzureRmContext  
> Connect-AzureRmAccount  
Connect-AzureRmAccount : Object reference not set to an instance of an object.
At line:1 char:1
+ Connect-AzureRmAccount
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Connect-AzureRmAccount], NullReferenceException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand

In my developer machine there is no problem connecting to the subscription and getting a context

Script/Steps for Reproduction

Clean installation of Windows 10 The following has been tried with running both as administrator and as non-priv user

> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
> Install-Module AzureRM -Scope CurrentUser

Now I reboot the machine, as I would otherwise get the above NullReferenceException

> Connect-AzureRmAccount

Account          :  
SubscriptionName :  
SubscriptionId   :  
TenantId         :  
Environment      :

Module Version

> Get-Module -ListAvailable

    Directory: C:\Users\chris\Documents\WindowsPowerShell\Modules

ModuleType Version    Name                                ExportedCommands                                             
---------- -------    ----                                ----------------                                             
Script     0.5.4      Azure.AnalysisServices              {Add-AzureAnalysisServicesAccount, Restart-AzureAnalysisSe...
Script     4.5.0      Azure.Storage                       {Get-AzureStorageTable, New-AzureStorageTableSASToken, New...
Script     6.8.1      AzureRM                                                                                          
Script     0.6.14     AzureRM.AnalysisServices            {Resume-AzureRmAnalysisServicesServer, Suspend-AzureRmAnal...
Script     6.1.5      AzureRM.ApiManagement               {Add-AzureRmApiManagementRegion, Get-AzureRmApiManagementS...
Script     0.1.8      AzureRM.ApplicationInsights         {Get-AzureRmApplicationInsights, New-AzureRmApplicationIns...
Script     5.1.1      AzureRM.Automation                  {Get-AzureRMAutomationHybridWorkerGroup, Get-AzureRmAutoma...
Script     4.0.10     AzureRM.Backup                      {Backup-AzureRmBackupItem, Enable-AzureRmBackupContainerRe...
Script     4.1.5      AzureRM.Batch                       {Remove-AzureRmBatchAccount, Get-AzureRmBatchAccount, Get-...
Script     0.14.6     AzureRM.Billing                     {Get-AzureRmBillingInvoice, Get-AzureRmBillingPeriod, Get-...
Script     5.0.5      AzureRM.Cdn                         {Get-AzureRmCdnProfile, Get-AzureRmCdnProfileSsoUrl, New-A...
Script     0.9.10     AzureRM.CognitiveServices           {Get-AzureRmCognitiveServicesAccount, Get-AzureRmCognitive...
Script     5.5.2      AzureRM.Compute                     {Remove-AzureRmAvailabilitySet, Get-AzureRmAvailabilitySet...
Script     0.3.7      AzureRM.Consumption                 {Get-AzureRmConsumptionBudget, Get-AzureRmConsumptionMarke...
Script     0.2.10     AzureRM.ContainerInstance           {New-AzureRmContainerGroup, Get-AzureRmContainerGroup, Rem...
Script     1.0.10     AzureRM.ContainerRegistry           {New-AzureRmContainerRegistry, Get-AzureRmContainerRegistr...
Script     5.0.3      AzureRM.DataFactories               {Remove-AzureRmDataFactory, Get-AzureRmDataFactoryRun, Get...
Script     0.5.10     AzureRM.DataFactoryV2               {Set-AzureRmDataFactoryV2, Update-AzureRmDataFactoryV2, Ge...
Script     5.1.4      AzureRM.DataLakeAnalytics           {Get-AzureRmDataLakeAnalyticsDataSource, New-AzureRmDataLa...
Script     6.1.2      AzureRM.DataLakeStore               {Get-AzureRmDataLakeStoreTrustedIdProvider, Remove-AzureRm...
Script     4.0.9      AzureRM.DevTestLabs                 {Get-AzureRmDtlAllowedVMSizesPolicy, Get-AzureRmDtlAutoShu...
Script     5.0.4      AzureRM.Dns                         {Get-AzureRmDnsRecordSet, New-AzureRmDnsRecordConfig, Remo...
Script     0.3.7      AzureRM.EventGrid                   {New-AzureRmEventGridTopic, Get-AzureRmEventGridTopic, Set...
Script     0.6.10     AzureRM.EventHub                    {New-AzureRmEventHubNamespace, Get-AzureRmEventHubNamespac...
Script     4.1.8      AzureRM.HDInsight                   {Get-AzureRmHDInsightJob, New-AzureRmHDInsightSqoopJobDefi...
Script     5.1.3      AzureRM.Insights                    {Get-AzureRmMetricDefinition, Get-AzureRmMetric, Remove-Az...
Script     3.1.8      AzureRM.IotHub                      {Add-AzureRmIotHubKey, Get-AzureRmIotHubEventHubConsumerGr...
Script     5.2.1      AzureRM.KeyVault                    {Add-AzureKeyVaultCertificate, Update-AzureKeyVaultCertifi...
Script     4.1.4      AzureRM.LogicApp                    {Get-AzureRmIntegrationAccountAgreement, Get-AzureRmIntegr...
Script     0.18.5     AzureRM.MachineLearning             {Move-AzureRmMlCommitmentAssociation, Get-AzureRmMlCommitm...
Script     0.4.8      AzureRM.MachineLearningCompute      {Get-AzureRmMlOpCluster, Get-AzureRmMlOpClusterKey, Test-A...
Script     0.2.5      AzureRM.MarketplaceOrdering         {Get-AzureRmMarketplaceTerms, Set-AzureRmMarketplaceTerms}   
Script     0.10.4     AzureRM.Media                       {Sync-AzureRmMediaServiceStorageKeys, Set-AzureRmMediaServ...
Script     6.6.1      AzureRM.Network                     {Add-AzureRmApplicationGatewayAuthenticationCertificate, G...
Script     5.0.3      AzureRM.NotificationHubs            {Get-AzureRmNotificationHub, Get-AzureRmNotificationHubAut...
Script     5.0.6      AzureRM.OperationalInsights         {New-AzureRmOperationalInsightsAzureActivityLogDataSource,...
Script     1.0.4      AzureRM.PolicyInsights              {Get-AzureRmPolicyEvent, Get-AzureRmPolicyState, Get-Azure...
Script     4.1.10     AzureRM.PowerBIEmbedded             {Remove-AzureRmPowerBIWorkspaceCollection, Get-AzureRmPowe...
Script     5.5.1      AzureRM.profile                     {Disable-AzureRmDataCollection, Disable-AzureRmContextAuto...
Script     4.1.8      AzureRM.RecoveryServices            {Get-AzureRmRecoveryServicesBackupProperty, Get-AzureRmRec...
Script     4.4.1      AzureRM.RecoveryServices.Backup     {Backup-AzureRmRecoveryServicesBackupItem, Get-AzureRmReco...
Script     0.2.9      AzureRM.RecoveryServices.SiteRec... {Edit-AzureRmRecoveryServicesAsrRecoveryPlan, Get-AzureRmR...
Script     5.0.5      AzureRM.RedisCache                  {Remove-AzureRmRedisCachePatchSchedule, New-AzureRmRedisCa...
Script     0.3.10     AzureRM.Relay                       {New-AzureRmRelayNamespace, Get-AzureRmRelayNamespace, Set...
Script     6.4.2      AzureRM.Resources                   {Get-AzureRmProviderOperation, Remove-AzureRmRoleAssignmen...
Script     0.16.10    AzureRM.Scheduler                   {Disable-AzureRmSchedulerJobCollection, Enable-AzureRmSche...
Script     0.6.11     AzureRM.ServiceBus                  {New-AzureRmServiceBusNamespace, Get-AzureRmServiceBusName...
Script     0.3.12     AzureRM.ServiceFabric               {Add-AzureRmServiceFabricApplicationCertificate, Add-Azure...
Script     4.11.3     AzureRM.Sql                         {Get-AzureRmSqlDatabaseTransparentDataEncryption, Get-Azur...
Script     5.0.4      AzureRM.Storage                     {Get-AzureRmStorageAccount, Get-AzureRmStorageAccountKey, ...
Script     4.0.10     AzureRM.StreamAnalytics             {Get-AzureRmStreamAnalyticsFunction, Get-AzureRmStreamAnal...
Script     4.0.5      AzureRM.Tags                        {Remove-AzureRmTag, Get-AzureRmTag, New-AzureRmTag}          
Script     4.1.1      AzureRM.TrafficManager              {Add-AzureRmTrafficManagerCustomHeaderToEndpoint, Remove-A...
Script     4.0.5      AzureRM.UsageAggregates             Get-UsageAggregates                                          
Script     5.0.9      AzureRM.Websites                    {Get-AzureRmAppServicePlan, Set-AzureRmAppServicePlan, New...

    Directory: C:\Program Files\WindowsPowerShell\Modules

ModuleType Version    Name                                ExportedCommands                                             
---------- -------    ----                                ----------------                                             
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     1.0.0.1    PowerShellGet                       {Install-Module, Find-Module, Save-Module, Update-Module...} 
Script     1.2        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.0.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        Defender                            {Get-MpPreference, Set-MpPreference, Add-MpPreference, Rem...
Manifest   1.0.0.0    DeliveryOptimization                {Get-DeliveryOptimizationStatus, Get-DeliveryOptimizationP...
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...
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   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   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   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...

Environment Data

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

Debug Output

> Connect-AzureRmAccount -Debug
DEBUG: 12:28:24 - ConnectAzureRmAccountCommand begin processing with ParameterSet 'UserWithSubscriptionId'.

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): a

Confirm
Are you sure you want to perform this action?
Performing the operation "log in" on target "User account in environment 'AzureCloud'".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): a
DEBUG: 12:28:27 - Autosave setting from startup session: 'CurrentUser'
DEBUG: 12:28:27 - No autosave setting detected in environment variable 'AzureRmContextAutoSave'.
DEBUG: 12:28:27 - Using Autosave scope 'CurrentUser'
DEBUG: [Common.Authentication]: Authenticating using configuration values: Domain: 'Common', Endpoint:
'https://login.microsoftonline.com/', ClientId: '1950a258-227b-4e31-a9cf-717495945fc2', ClientRedirect:
'urn:ietf:wg:oauth:2.0:oob', ResourceClientUri: 'https://management.core.windows.net/', ValidateAuthrity: 'True'
DEBUG: [Common.Authentication]: Acquiring token using context with Authority
'https://login.microsoftonline.com/Common/', CorrelationId: '00000000-0000-0000-0000-000000000000', ValidateAuthority:
'True'
DEBUG: [Common.Authentication]: Acquiring token using AdalConfiguration with Domain: 'Common', AdEndpoint:
'https://login.microsoftonline.com/', ClientId: '1950a258-227b-4e31-a9cf-717495945fc2', ClientRedirectUri:
urn:ietf:wg:oauth:2.0:oob
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:27: fe324f89-b581-4b16-a6dc-91f0d1e91f62 - AcquireTokenHandlerBase: === Token Acquisition
started:
 Authority: https://login.microsoftonline.com/Common/
 Resource: https://management.core.windows.net/
 ClientId: 1950a258-227b-4e31-a9cf-717495945fc2
 CacheType: Microsoft.Azure.Commands.Common.Authentication.ProtectedFileTokenCache (1 items)
 Authentication Target: User

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 :
DEBUG: 09/05/2018 10:28:27:  - WindowsFormsWebAuthenticationDialogBase: Navigating to
'https://login.microsoftonline.com/Common/oauth2/authorize?resource=https://management.core.windows.net/&client_id=1950
a258-227b-4e31-a9cf-717495945fc2&response_type=code&haschrome=1&redirect_uri=urn:ietf:wg:oauth:2.0:oob&client-request-i
d=fe324f89-b581-4b16-a6dc-91f0d1e91f62&prompt=login&x-client-SKU=.NET&x-client-Ver=2.28.3.860&x-client-CPU=x64&x-client
-OS=Microsoft Windows NT 10.0.17134.0&site_id=501358&display=popup'.
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 :
DEBUG: 09/05/2018 10:28:27:  - WindowsFormsWebAuthenticationDialogBase: Navigated to
'https://login.microsoftonline.com/Common/oauth2/authorize?resource=https://management.core.windows.net/&client_id=1950
a258-227b-4e31-a9cf-717495945fc2&response_type=code&haschrome=1&redirect_uri=urn:ietf:wg:oauth:2.0:oob&client-request-i
d=fe324f89-b581-4b16-a6dc-91f0d1e91f62&prompt=login&x-client-SKU=.NET&x-client-Ver=2.28.3.860&x-client-CPU=x64&x-client
-OS=Microsoft Windows NT 10.0.17134.0&site_id=501358&display=popup'.
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 :
DEBUG: 09/05/2018 10:28:36:  - WindowsFormsWebAuthenticationDialogBase: Navigating to
'https://login.microsoftonline.com/common/login'.
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 :
DEBUG: 09/05/2018 10:28:37:  - WindowsFormsWebAuthenticationDialogBase: WebBrowser state: IsBusy: True, ReadyState:
Complete, Created: True, Disposing: False, IsDisposed: False, IsOffline: False
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 :
DEBUG: 09/05/2018 10:28:37:  - WindowsFormsWebAuthenticationDialogBase: WebBrowser state (after Stop): IsBusy: False,
ReadyState: Complete, Created: True, Disposing: False, IsDisposed: False, IsOffline: False
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:37:  - TokenCache: Deserialized 1 items to token cache.
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 :
DEBUG: 09/05/2018 10:28:37: fe324f89-b581-4b16-a6dc-91f0d1e91f62 - TokenCache: Storing token in the cache...
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 :
DEBUG: 09/05/2018 10:28:37: fe324f89-b581-4b16-a6dc-91f0d1e91f62 - TokenCache: An item was stored in the cache
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:37: fe324f89-b581-4b16-a6dc-91f0d1e91f62 - AcquireTokenHandlerBase: === Token Acquisition
finished successfully. An access token was retuned:
 Access Token Hash: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 Refresh Token Hash: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 Expiration Time: 09/05/2018 11:28:36 +00:00
 User Hash: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:37:  - TokenCache: Serializing token cache with 1 items.
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

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

Headers:
x-ms-client-request-id        : 9e78a9a1-46f2-4fa5-9253-996c90ebb6f2
accept-language               : en-US

Body:

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

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-tenant-reads: 11999
x-ms-request-id               : bc55d957-297b-49b3-b33f-10370147e60d
x-ms-correlation-request-id   : bc55d957-297b-49b3-b33f-10370147e60d
x-ms-routing-request-id       : WESTEUROPE:20180905T102837Z:bc55d957-297b-49b3-b33f-10370147e60d
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
Cache-Control                 : no-cache
Date                          : Wed, 05 Sep 2018 10:28:36 GMT

Body:
{
  "value": [
    {
      "id": "/tenants/9ad2a31c-1f19-4099-9fca-0565a1808184",
      "tenantId": "9ad2a31c-1f19-4099-9fca-0565a1808184"
    }
  ]
}

DEBUG: [Common.Authentication]: Authenticating using configuration values: Domain:
'9ad2a31c-1f19-4099-9fca-0565a1808184', Endpoint: 'https://login.microsoftonline.com/', ClientId:
'1950a258-227b-4e31-a9cf-717495945fc2', ClientRedirect: 'urn:ietf:wg:oauth:2.0:oob', ResourceClientUri:
'https://management.core.windows.net/', ValidateAuthrity: 'True'
DEBUG: [Common.Authentication]: Acquiring token using context with Authority
'https://login.microsoftonline.com/9ad2a31c-1f19-4099-9fca-0565a1808184/', CorrelationId:
'00000000-0000-0000-0000-000000000000', ValidateAuthority: 'True'
DEBUG: [Common.Authentication]: Acquiring token using AdalConfiguration with Domain:
'9ad2a31c-1f19-4099-9fca-0565a1808184', AdEndpoint: 'https://login.microsoftonline.com/', ClientId:
'1950a258-227b-4e31-a9cf-717495945fc2', ClientRedirectUri: urn:ietf:wg:oauth:2.0:oob
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:37: 25b076f1-c63b-44d5-b918-178f19b5eff9 - AcquireTokenHandlerBase: === Token Acquisition
started:
 Authority: https://login.microsoftonline.com/9ad2a31c-1f19-4099-9fca-0565a1808184/
 Resource: https://management.core.windows.net/
 ClientId: 1950a258-227b-4e31-a9cf-717495945fc2
 CacheType: Microsoft.Azure.Commands.Common.Authentication.ProtectedFileTokenCache (1 items)
 Authentication Target: User

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:37:  - TokenCache: Deserialized 1 items to token cache.
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 :
DEBUG: 09/05/2018 10:28:37: 25b076f1-c63b-44d5-b918-178f19b5eff9 - TokenCache: Looking up cache for a token...
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:37: 25b076f1-c63b-44d5-b918-178f19b5eff9 - TokenCache: An item matching the requested resource
was found in the cache
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 :
DEBUG: 09/05/2018 10:28:37: 25b076f1-c63b-44d5-b918-178f19b5eff9 - TokenCache: 59.9776044266667 minutes left until
token in cache expires
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:37: 25b076f1-c63b-44d5-b918-178f19b5eff9 - TokenCache: A matching item (access token or refresh
 token or both) was found in the cache
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:37: 25b076f1-c63b-44d5-b918-178f19b5eff9 - AcquireTokenHandlerBase: === Token Acquisition
finished successfully. An access token was retuned:
 Access Token Hash: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 Refresh Token Hash: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 Expiration Time: 09/05/2018 11:28:36 +00:00
 User Hash: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

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

Headers:
x-ms-client-request-id        : 244c5b01-a7af-4353-8f86-a8c7c4c9d000
accept-language               : en-US

Body:

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

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-tenant-reads: 11997
x-ms-request-id               : 6a582124-a488-4856-9071-f9d82b08f167
x-ms-correlation-request-id   : 6a582124-a488-4856-9071-f9d82b08f167
x-ms-routing-request-id       : WESTEUROPE:20180905T102837Z:6a582124-a488-4856-9071-f9d82b08f167
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
Cache-Control                 : no-cache
Date                          : Wed, 05 Sep 2018 10:28:36 GMT

Body:
{
  "value": []
}

DEBUG: [Common.Authentication]: Authenticating using configuration values: Domain:
'9ad2a31c-1f19-4099-9fca-0565a1808184', Endpoint: 'https://login.microsoftonline.com/', ClientId:
'1950a258-227b-4e31-a9cf-717495945fc2', ClientRedirect: 'urn:ietf:wg:oauth:2.0:oob', ResourceClientUri:
'https://management.core.windows.net/', ValidateAuthrity: 'True'
DEBUG: [Common.Authentication]: Acquiring token using context with Authority
'https://login.microsoftonline.com/9ad2a31c-1f19-4099-9fca-0565a1808184/', CorrelationId:
'00000000-0000-0000-0000-000000000000', ValidateAuthority: 'True'
DEBUG: [Common.Authentication]: Acquiring token using AdalConfiguration with Domain:
'9ad2a31c-1f19-4099-9fca-0565a1808184', AdEndpoint: 'https://login.microsoftonline.com/', ClientId:
'1950a258-227b-4e31-a9cf-717495945fc2', ClientRedirectUri: urn:ietf:wg:oauth:2.0:oob
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:37: e6ec5589-ac6c-4f66-9308-c52c69d4c387 - AcquireTokenHandlerBase: === Token Acquisition
started:
 Authority: https://login.microsoftonline.com/9ad2a31c-1f19-4099-9fca-0565a1808184/
 Resource: https://management.core.windows.net/
 ClientId: 1950a258-227b-4e31-a9cf-717495945fc2
 CacheType: Microsoft.Azure.Commands.Common.Authentication.ProtectedFileTokenCache (1 items)
 Authentication Target: User

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:37:  - TokenCache: Deserialized 1 items to token cache.
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 :
DEBUG: 09/05/2018 10:28:37: e6ec5589-ac6c-4f66-9308-c52c69d4c387 - TokenCache: Looking up cache for a token...
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:37: e6ec5589-ac6c-4f66-9308-c52c69d4c387 - TokenCache: An item matching the requested resource
was found in the cache
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 :
DEBUG: 09/05/2018 10:28:37: e6ec5589-ac6c-4f66-9308-c52c69d4c387 - TokenCache: 59.97421914 minutes left until token in
cache expires
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:37: e6ec5589-ac6c-4f66-9308-c52c69d4c387 - TokenCache: A matching item (access token or refresh
 token or both) was found in the cache
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:37: e6ec5589-ac6c-4f66-9308-c52c69d4c387 - AcquireTokenHandlerBase: === Token Acquisition
finished successfully. An access token was retuned:
 Access Token Hash: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 Refresh Token Hash: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 Expiration Time: 09/05/2018 11:28:36 +00:00
 User Hash: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

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

Headers:
x-ms-client-request-id        : a165cc95-143d-4510-8e5c-49d053cb2b61
accept-language               : en-US

Body:

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

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-tenant-reads: 11999
x-ms-request-id               : c44a451e-ab30-4626-b824-59f6899520dd
x-ms-correlation-request-id   : c44a451e-ab30-4626-b824-59f6899520dd
x-ms-routing-request-id       : WESTEUROPE:20180905T102837Z:c44a451e-ab30-4626-b824-59f6899520dd
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
Cache-Control                 : no-cache
Date                          : Wed, 05 Sep 2018 10:28:36 GMT

Body:
{
  "value": [
    {
      "id": "/tenants/9ad2a31c-1f19-4099-9fca-0565a1808184",
      "tenantId": "9ad2a31c-1f19-4099-9fca-0565a1808184"
    }
  ]
}

DEBUG: [Common.Authentication]: Authenticating using configuration values: Domain:
'9ad2a31c-1f19-4099-9fca-0565a1808184', Endpoint: 'https://login.microsoftonline.com/', ClientId:
'1950a258-227b-4e31-a9cf-717495945fc2', ClientRedirect: 'urn:ietf:wg:oauth:2.0:oob', ResourceClientUri:
'https://management.core.windows.net/', ValidateAuthrity: 'True'
DEBUG: [Common.Authentication]: Acquiring token using context with Authority
'https://login.microsoftonline.com/9ad2a31c-1f19-4099-9fca-0565a1808184/', CorrelationId:
'00000000-0000-0000-0000-000000000000', ValidateAuthority: 'True'
DEBUG: [Common.Authentication]: Acquiring token using AdalConfiguration with Domain:
'9ad2a31c-1f19-4099-9fca-0565a1808184', AdEndpoint: 'https://login.microsoftonline.com/', ClientId:
'1950a258-227b-4e31-a9cf-717495945fc2', ClientRedirectUri: urn:ietf:wg:oauth:2.0:oob
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:38: ca721844-991d-4e00-b65e-c28008f88598 - AcquireTokenHandlerBase: === Token Acquisition
started:
 Authority: https://login.microsoftonline.com/9ad2a31c-1f19-4099-9fca-0565a1808184/
 Resource: https://management.core.windows.net/
 ClientId: 1950a258-227b-4e31-a9cf-717495945fc2
 CacheType: Microsoft.Azure.Commands.Common.Authentication.ProtectedFileTokenCache (1 items)
 Authentication Target: User

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:38:  - TokenCache: Deserialized 1 items to token cache.
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 :
DEBUG: 09/05/2018 10:28:38: ca721844-991d-4e00-b65e-c28008f88598 - TokenCache: Looking up cache for a token...
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:38: ca721844-991d-4e00-b65e-c28008f88598 - TokenCache: An item matching the requested resource
was found in the cache
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 :
DEBUG: 09/05/2018 10:28:38: ca721844-991d-4e00-b65e-c28008f88598 - TokenCache: 59.9663969733333 minutes left until
token in cache expires
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:38: ca721844-991d-4e00-b65e-c28008f88598 - TokenCache: A matching item (access token or refresh
 token or both) was found in the cache
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 :
DEBUG: 09/05/2018 10:28:38: ca721844-991d-4e00-b65e-c28008f88598 - AcquireTokenHandlerBase: === Token Acquisition
finished successfully. An access token was retuned:
 Access Token Hash: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 Refresh Token Hash: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 Expiration Time: 09/05/2018 11:28:36 +00:00
 User Hash: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

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

Headers:
x-ms-client-request-id        : aa7532d5-60c8-4eed-8c70-c7fcf415078c
accept-language               : en-US

Body:

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

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-tenant-reads: 11999
x-ms-request-id               : 9d5473d0-535b-478b-bcc7-cada59f2f4b1
x-ms-correlation-request-id   : 9d5473d0-535b-478b-bcc7-cada59f2f4b1
x-ms-routing-request-id       : WESTEUROPE:20180905T102837Z:9d5473d0-535b-478b-bcc7-cada59f2f4b1
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
Cache-Control                 : no-cache
Date                          : Wed, 05 Sep 2018 10:28:37 GMT

Body:
{
  "value": []
}

Account          :
SubscriptionName :
SubscriptionId   :
TenantId         :
Environment      :

DEBUG: AzureQoSEvent: CommandName - Connect-AzureRmAccount; IsSuccess - True; Duration - 00:00:14.3868954; Exception -
;
DEBUG: Finish sending metric.
DEBUG: 12:28:39 - ConnectAzureRmAccountCommand end processing.
DEBUG: 12:28:39 - ConnectAzureRmAccountCommand end processing.

> Get-AzureRmContext
DEBUG: 12:40:32 - GetAzureRMContextCommand begin processing with ParameterSet 'GetSingleContext'.
DEBUG: AzureQoSEvent: CommandName - Get-AzureRmContext; IsSuccess - True; Duration - 00:00:00.0073244; Exception - ;
DEBUG: Finish sending metric.
DEBUG: 12:40:35 - GetAzureRMContextCommand end processing.
DEBUG: 12:40:35 - GetAzureRMContextCommand end processing.
markcowl commented 6 years ago

@chlillelund Generally, you need to have some authorization to RM resources in order to use the Azure PowerShell cmdlets. The ADS functionality we provide is tightly coupled with usage of AD objects inside Azure Resource Manager.

The AzureAD cmdlets porvide more general functionality for manipulating AAD and Graph objects: https://www.powershellgallery.com/packages/AzureAD/2.0.1.16

chlillelund commented 6 years ago

@markcowl Thanks for your answer. I know it might be a bit overkill to use AzureRM, but it provides a lot more functionality than AzureAD. For example, I use AzureRM.Profile to get an access token so that I can grant admin consent to my application (http://www.lieben.nu/liebensraum/2018/04/how-to-grant-oauth2-permissions-to-an-azure-ad-application-using-powershell-unattended-silently/). The "fun" thing about this, and the reason for me creating the bug report is that it works just fine on my developer laptop, where I have e.g. Visual Studio installed. And as stated in the bug report, it also works just fine on the clean Win10 machine, if I just log in with an account that does have an Azure subscription, and then log in with my O365 admin account.

mattmcspirit commented 5 years ago

I had the same issue as you - Get-AzureRmContext would return blank for an Azure AD account that had no subscription associated, so I couldn't get a refreshToken, grant permissions etc.

Then I figured out this:

$azureDirectoryTenantName = "domain.com"
$tenantId = (Invoke-RestMethod "https://login.microsoftonline.com/$($azureDirectoryTenantName)/.well-known/openid-configuration").issuer.TrimEnd('/').Split('/')[-1]
Add-AzureRmAccount -EnvironmentName "AzureCloud" -TenantId $tenantId -Credential <creds> -ErrorAction Stop
$refreshToken = @([Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.TokenCache.ReadItems() | Where-Object {$_.tenantId -eq $tenantId -and $_.ExpiresOn -gt (Get-Date)})[0].RefreshToken
$refreshtoken = $refreshtoken.Split("`n")[0]
$body = "grant_type=refresh_token&refresh_token=$($refreshToken)&resource=74658136-14ec-4630-ad9b-26e160ff0fc6"
$apiToken = Invoke-RestMethod "https://login.windows.net/$tenantId/oauth2/token" -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
                    $header = @{
                        'Authorization'          = 'Bearer ' + $apiToken.access_token
                        'X-Requested-With'       = 'XMLHttpRequest'
                        'x-ms-client-request-id' = [guid]::NewGuid()
                        'x-ms-correlation-id'    = [guid]::NewGuid()
                    }
                    $url = "https://main.iam.ad.ext.azure.com/api/RegisteredApplications/$identityApplicationID/Consent?onBehalfOfAll=true"
Invoke-RestMethod –Uri $url –Headers $header –Method POST -ErrorAction Stop

This works for my needs, and overcame the issue of trying to automate granting of permissions when the Azure Ad account had no subscription associated.