azure-powershell icon indicating copy to clipboard operation
azure-powershell copied to clipboard

Multiple logins will cause Select-AzureRmSubscription to select default subscription

Open tran-barry opened this issue 9 years ago • 11 comments

Cmdlet(s)

  • Import-AzureRmContext
  • Select-AzureRmSubscription

PowerShell Version

  • 5.1.15063.296

Module Version

  • 4.4.0

OS Version

  • 10.0.15063.296

Description

If you login multiple times within the same console session, every 2nd login will cause Select-AzureRmSubscription to select the default subscription associated with your login instead of the one you specify.

This is only an issue in 4.4.0. Downgrading to 4.3.1 resolved the issue.

Also, having an azure profile with multiple subscriptions defined would work around the issue.

Debug Output

First Invocation (correct):

PS C:\Users\barry.tran> Import-AzureRmContext $pathToProfile; Select-AzureRmSubscription -subscriptionName Sandbox
DEBUG: 12:51:11 PM - Autosave setting from startup session: 'Process'
DEBUG: 12:51:11 PM - No autosave setting detected in environment variable 'AzureRmContextAutoSave'. 
DEBUG: 12:51:11 PM - Using Autosave scope 'Process'


Account          : [email protected]
SubscriptionName : Operations
SubscriptionId   : ********-****-****-****-************
TenantId         : ********-****-****-****-************
Environment      : AzureCloud

DEBUG: 12:51:11 PM - ImportAzureRMContextCommand end processing.
DEBUG: 12:51:11 PM - ImportAzureRMContextCommand end processing.
DEBUG: 12:51:11 PM - SetAzureRMContextCommand begin processing with ParameterSet 'Subscription'.
DEBUG: 12:51:11 PM - using account id '[email protected]'...
DEBUG: 12:51:11 PM - Autosave setting from startup session: 'Process'
DEBUG: 12:51:11 PM - No autosave setting detected in environment variable 'AzureRmContextAutoSave'. 
DEBUG: 12:51:11 PM - Using Autosave scope 'Process'
DEBUG: [Common.Authentication]: Authenticating using configuration values: Domain: '********-****-****-****-************', En
dpoint: 'https://login.microsoftonline.com/', ClientId: '********-****-****-****-************', 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/********-****-****-****-************/', CorrelationId: '00000000-0000-0000-0000-000000000000', ValidateAuthority: 'True'
DEBUG: [Common.Authentication]: Acquiring token using AdalConfiguration with Domain: '********-****-****-****-************', 
AdEndpoint: 'https://login.microsoftonline.com/', ClientId: '********-****-****-****-************', ClientRedirectUri: urn:ie
tf:wg:oauth:2.0:oob
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:11: ********-****-****-****-************ - AcquireTokenHandlerBase: === Token Acquisition started:
	Authority: https://login.microsoftonline.com/********-****-****-****-************/
	Resource: https://management.core.windows.net/
	ClientId: ********-****-****-****-************
	CacheType: Microsoft.Azure.Commands.Common.Authentication.AuthenticationStoreTokenCache (1 items)
	Authentication Target: User
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:11: ********-****-****-****-************ - TokenCache: Looking up cache for a token...

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:11: ********-****-****-****-************ - TokenCache: An item matching the requested resource was fo
und in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:11: ********-****-****-****-************ - TokenCache: An expired or near expiry token was found in t
he cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:11: ********-****-****-****-************ - TokenCache: A matching item (access token or refresh token
 or both) was found in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:11: ********-****-****-****-************ - <RefreshAccessTokenAsync>d__11: Refreshing access token...


DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Error: 4 : 
DEBUG: 10/04/2017 19:51:12: ********-****-****-****-************ - <RefreshAccessTokenAsync>d__11: Microsoft.IdentityModel.Cl
ients.ActiveDirectory.AdalServiceException: AADSTS70002: Error validating credentials. AADSTS70008: The refresh token has exp
ired due to inactivity. The token was issued on 2017-09-15T20:51:21.2640938Z and was inactive for 14.00:00:00.
Trace ID: ********-****-****-****-************
Correlation ID: ********-****-****-****-************
Timestamp: 2017-10-04 19:51:12Z ---> System.Net.WebException: The remote server returned an error: (400) Bad Request.
   at System.Net.HttpWebRequest.GetResponse()
   at Microsoft.IdentityModel.Clients.ActiveDirectory.HttpWebRequestWrapper.<GetResponseSyncOrAsync>d__2.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.IdentityModel.Clients.ActiveDirectory.HttpHelper.<SendPostRequestAndDeserializeJsonResponseAsync>d__0`1.MoveN
ext()
   --- End of inner exception stack trace ---
   at Microsoft.IdentityModel.Clients.ActiveDirectory.HttpHelper.<SendPostRequestAndDeserializeJsonResponseAsync>d__0`1.MoveN
ext()
--- 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.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<SendHttpMessageAsync>d__15.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.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<SendTokenRequestByRefreshTokenAsync>d__d.MoveN
ext()
--- 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.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<RefreshAccessTokenAsync>d__11.MoveNext()
	ErrorCode: invalid_grant
	StatusCode: 400

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:12:  - WindowsFormsWebAuthenticationDialogBase: Navigating to 'https://login.microsoftonline.com/****
****-****-****-****-************/oauth2/authorize?resource=https://management.core.windows.net/&client_id=********-****-****-
****-************&response_type=code&haschrome=1&redirect_uri=urn:ietf:wg:oauth:2.0:oob&[email protected]&client
-request-id=********-****-****-****-************&prompt=attempt_none&x-client-SKU=.NET&x-client-Ver=2.28.3.860&x-client-CPU=x
64&x-client-OS=Microsoft Windows NT 10.0.15063.0&site_id=501358&display=popup'.

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:13: ********-****-****-****-************ - TokenCache: Storing token in the cache...

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:13: ********-****-****-****-************ - TokenCache: An item was stored in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:13: ********-****-****-****-************ - AcquireTokenHandlerBase: === Token Acquisition finished su
ccessfully. An access token was retuned:
	Access Token Hash: ********************************************
	Refresh Token Hash: ********************************************
	Expiration Time: 10/04/2017 20:51:12 +00:00
	User Hash: ********************************************
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:13:  - 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        : ********-****-****-****-************
accept-language               : en-US

Body:



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

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-tenant-reads: 14995
x-ms-request-id               : ********-****-****-****-************
x-ms-correlation-request-id   : ********-****-****-****-************
x-ms-routing-request-id       : NORTHCENTRALUS:20171004T195113Z:********-****-****-****-************
Strict-Transport-Security     : max-age=31536000; includeSubDomains
Cache-Control                 : no-cache
Date                          : Wed, 04 Oct 2017 19:51:12 GMT

Body:
{
  "value": [
    {
      "id": "/tenants/********-****-****-****-************",
      "tenantId": "********-****-****-****-************"
    }
  ]
}


DEBUG: [Common.Authentication]: Authenticating using configuration values: Domain: '********-****-****-****-************', En
dpoint: 'https://login.microsoftonline.com/', ClientId: '********-****-****-****-************', 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/********-****
-****-****-************/', CorrelationId: '00000000-0000-0000-0000-000000000000', ValidateAuthority: 'True'
DEBUG: [Common.Authentication]: Acquiring token using AdalConfiguration with Domain: '********-****-****-****-************', 
AdEndpoint: 'https://login.microsoftonline.com/', ClientId: '********-****-****-****-************', ClientRedirectUri: urn:ie
tf:wg:oauth:2.0:oob
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:13: ********-****-****-****-************ - AcquireTokenHandlerBase: === Token Acquisition started:
	Authority: https://login.microsoftonline.com/********-****-****-****-************/
	Resource: https://management.core.windows.net/
	ClientId: ********-****-****-****-************
	CacheType: Microsoft.Azure.Commands.Common.Authentication.AuthenticationStoreTokenCache (1 items)
	Authentication Target: User
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:13: ********-****-****-****-************ - TokenCache: Looking up cache for a token...

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:13: ********-****-****-****-************ - TokenCache: An item matching the requested resource was fo
und in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:13: ********-****-****-****-************ - TokenCache: 59.9763066116667 minutes left until token in c
ache expires

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:13: ********-****-****-****-************ - TokenCache: A matching item (access token or refresh token
 or both) was found in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:13: ********-****-****-****-************ - AcquireTokenHandlerBase: === Token Acquisition finished su
ccessfully. An access token was retuned:
	Access Token Hash: **********************************
	Refresh Token Hash: ********************************************
	Expiration Time: 10/04/2017 20:51:12 +00:00
	User Hash: ********************************************
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:13:  - TokenCache: Serializing token cache with 1 items.

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

HTTP Method:
GET

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

Headers:
x-ms-client-request-id        : ********-****-****-****-************
accept-language               : en-US

Body:



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

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-tenant-reads: 14995
x-ms-request-id               : ********-****-****-****-************
x-ms-correlation-request-id   : ********-****-****-****-************
x-ms-routing-request-id       : NORTHCENTRALUS:20171004T195113Z:********-****-****-****-************
Strict-Transport-Security     : max-age=31536000; includeSubDomains
Cache-Control                 : no-cache
Date                          : Wed, 04 Oct 2017 19:51:12 GMT

Body:
{
  "value": [
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "Operations",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "Performance",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "Sandbox",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "General Development",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "Development",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "General Production",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "Integration",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "Production",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "SpecialProjects",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "RoleBased"
    }
  ]
}



Name               : [[email protected], ********-****-****-****-************]
Account            : [email protected]
Environment        : AzureCloud
Subscription       : ********-****-****-****-************
Tenant             : ********-****-****-****-************
TokenCache         : Microsoft.Azure.Commands.Common.Authentication.AuthenticationStoreTokenCache
VersionProfile     : 
ExtendedProperties : {}

DEBUG: AzureQoSEvent: CommandName - Set-AzureRmContext; IsSuccess - True; Duration - 00:00:02.1211251; Exception - ;
DEBUG: Finish sending metric.
DEBUG: 12:51:14 PM - SetAzureRMContextCommand end processing.
DEBUG: 12:51:14 PM - SetAzureRMContextCommand end processing.

Second Invocation (Incorrect SubscriptionId):

PS C:\Users\barry.tran> Import-AzureRmContext $pathToProfile; Select-AzureRmSubscription -subscriptionName Sandbox
DEBUG: 12:51:17 PM - Autosave setting from startup session: 'Process'
DEBUG: 12:51:17 PM - No autosave setting detected in environment variable 'AzureRmContextAutoSave'. 
DEBUG: 12:51:17 PM - Using Autosave scope 'Process'


Account          : [email protected]
SubscriptionName : Operations
SubscriptionId   : ********-****-****-****-************
TenantId         : ********-****-****-****-************
Environment      : AzureCloud

DEBUG: 12:51:17 PM - ImportAzureRMContextCommand end processing.
DEBUG: 12:51:17 PM - ImportAzureRMContextCommand end processing.
DEBUG: 12:51:17 PM - SetAzureRMContextCommand begin processing with ParameterSet 'Subscription'.
DEBUG: 12:51:17 PM - using account id '[email protected]'...
DEBUG: 12:51:17 PM - Autosave setting from startup session: 'Process'
DEBUG: 12:51:17 PM - No autosave setting detected in environment variable 'AzureRmContextAutoSave'. 
DEBUG: 12:51:17 PM - Using Autosave scope 'Process'
DEBUG: [Common.Authentication]: Authenticating using configuration values: Domain: '********-****-****-****-************', En
dpoint: 'https://login.microsoftonline.com/', ClientId: '********-****-****-****-************', 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/********-****
-****-****-************/', CorrelationId: '00000000-0000-0000-0000-000000000000', ValidateAuthority: 'True'
DEBUG: [Common.Authentication]: Acquiring token using AdalConfiguration with Domain: '********-****-****-****-************', 
AdEndpoint: 'https://login.microsoftonline.com/', ClientId: '********-****-****-****-************', ClientRedirectUri: urn:ie
tf:wg:oauth:2.0:oob
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:17: ********-****-****-****-************ - AcquireTokenHandlerBase: === Token Acquisition started:
	Authority: https://login.microsoftonline.com/********-****-****-****-************/
	Resource: https://management.core.windows.net/
	ClientId: ********-****-****-****-************
	CacheType: Microsoft.Azure.Commands.Common.Authentication.AuthenticationStoreTokenCache (1 items)
	Authentication Target: User
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:17: ********-****-****-****-************ - TokenCache: Looking up cache for a token...

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:17: ********-****-****-****-************ - TokenCache: An item matching the requested resource was fo
und in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:17: ********-****-****-****-************ - TokenCache: An expired or near expiry token was found in t
he cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:17: ********-****-****-****-************ - TokenCache: A matching item (access token or refresh token
 or both) was found in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:17: ********-****-****-****-************ - <RefreshAccessTokenAsync>d__11: Refreshing access token...


DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Error: 4 : 
DEBUG: 10/04/2017 19:51:17: ********-****-****-****-************ - <RefreshAccessTokenAsync>d__11: Microsoft.IdentityModel.Cl
ients.ActiveDirectory.AdalServiceException: AADSTS70002: Error validating credentials. AADSTS70008: The refresh token has exp
ired due to inactivity. The token was issued on 2017-09-15T20:51:21.2640938Z and was inactive for 14.00:00:00.
Trace ID: d3867e13-53e7-4433-b303-a6c4552c3400
Correlation ID: ********-****-****-****-************
Timestamp: 2017-10-04 19:51:16Z ---> System.Net.WebException: The remote server returned an error: (400) Bad Request.
   at System.Net.HttpWebRequest.GetResponse()
   at Microsoft.IdentityModel.Clients.ActiveDirectory.HttpWebRequestWrapper.<GetResponseSyncOrAsync>d__2.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.IdentityModel.Clients.ActiveDirectory.HttpHelper.<SendPostRequestAndDeserializeJsonResponseAsync>d__0`1.MoveN
ext()
   --- End of inner exception stack trace ---
   at Microsoft.IdentityModel.Clients.ActiveDirectory.HttpHelper.<SendPostRequestAndDeserializeJsonResponseAsync>d__0`1.MoveN
ext()
--- 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.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<SendHttpMessageAsync>d__15.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.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<SendTokenRequestByRefreshTokenAsync>d__d.MoveN
ext()
--- 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.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<RefreshAccessTokenAsync>d__11.MoveNext()
	ErrorCode: invalid_grant
	StatusCode: 400

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:18:  - WindowsFormsWebAuthenticationDialogBase: Navigating to 'https://login.microsoftonline.com/****
****-****-****-****-************/oauth2/authorize?resource=https://management.core.windows.net/&client_id=********-****-****-
****-************&response_type=code&haschrome=1&redirect_uri=urn:ietf:wg:oauth:2.0:oob&[email protected]&client
-request-id=********-****-****-****-************&prompt=attempt_none&x-client-SKU=.NET&x-client-Ver=2.28.3.860&x-client-CPU=x
64&x-client-OS=Microsoft Windows NT 10.0.15063.0&site_id=501358&display=popup'.

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:18: ********-****-****-****-************ - TokenCache: Storing token in the cache...

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:18: ********-****-****-****-************ - TokenCache: An item was stored in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:18: ********-****-****-****-************ - AcquireTokenHandlerBase: === Token Acquisition finished su
ccessfully. An access token was retuned:
	Access Token Hash: ********************************************
	Refresh Token Hash: ********************************************
	Expiration Time: 10/04/2017 20:51:17 +00:00
	User Hash: ********************************************
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:18:  - 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        : d274d985-4fd1-4e76-88ed-4278d7b144a3
accept-language               : en-US

Body:



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

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-tenant-reads: 14994
x-ms-request-id               : ********-****-****-****-************
x-ms-correlation-request-id   : ********-****-****-****-************
x-ms-routing-request-id       : NORTHCENTRALUS:20171004T195118Z:********-****-****-****-************
Strict-Transport-Security     : max-age=31536000; includeSubDomains
Cache-Control                 : no-cache
Date                          : Wed, 04 Oct 2017 19:51:18 GMT

Body:
{
  "value": [
    {
      "id": "/tenants/********-****-****-****-************",
      "tenantId": "********-****-****-****-************"
    }
  ]
}


DEBUG: [Common.Authentication]: Authenticating using configuration values: Domain: '********-****-****-****-************', En
dpoint: 'https://login.microsoftonline.com/', ClientId: '********-****-****-****-************', 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/********-****
-****-****-************/', CorrelationId: '00000000-0000-0000-0000-000000000000', ValidateAuthority: 'True'
DEBUG: [Common.Authentication]: Acquiring token using AdalConfiguration with Domain: '********-****-****-****-************', 
AdEndpoint: 'https://login.microsoftonline.com/', ClientId: '********-****-****-****-************', ClientRedirectUri: urn:ie
tf:wg:oauth:2.0:oob
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:19: ********-****-****-****-************ - AcquireTokenHandlerBase: === Token Acquisition started:
	Authority: https://login.microsoftonline.com/********-****-****-****-************/
	Resource: https://management.core.windows.net/
	ClientId: ********-****-****-****-************
	CacheType: Microsoft.Azure.Commands.Common.Authentication.AuthenticationStoreTokenCache (1 items)
	Authentication Target: User
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:19: ********-****-****-****-************ - TokenCache: Looking up cache for a token...

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:19: ********-****-****-****-************ - TokenCache: An item matching the requested resource was fo
und in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 10/04/2017 19:51:19: ********-****-****-****-************ - TokenCache: 59.9751672683333 minutes left until token in c
ache expires

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:19: ********-****-****-****-************ - TokenCache: A matching item (access token or refresh token
 or both) was found in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:19: ********-****-****-****-************ - AcquireTokenHandlerBase: === Token Acquisition finished su
ccessfully. An access token was retuned:
	Access Token Hash: ********************************************
	Refresh Token Hash: ********************************************
	Expiration Time: 10/04/2017 20:51:17 +00:00
	User Hash: ********************************************
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 10/04/2017 19:51:19:  - TokenCache: Serializing token cache with 1 items.

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

HTTP Method:
GET

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

Headers:
x-ms-client-request-id        : ********-****-****-****-************
accept-language               : en-US

Body:



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

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-tenant-reads: 14996
x-ms-request-id               : ********-****-****-****-************
x-ms-correlation-request-id   : ********-****-****-****-************
x-ms-routing-request-id       : NORTHCENTRALUS:20171004T195119Z:********-****-****-****-************
Strict-Transport-Security     : max-age=31536000; includeSubDomains
Cache-Control                 : no-cache
Date                          : Wed, 04 Oct 2017 19:51:19 GMT

Body:
{
  "value": [
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "Operations",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "Performance",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "Sandbox",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "General Development",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "Development",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "General Production",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "Integration",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "Legacy, RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "Production",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "RoleBased"
    },
    {
      "id": "/subscriptions/********-****-****-****-************",
      "subscriptionId": "********-****-****-****-************",
      "displayName": "SpecialProjects",
      "state": "Enabled",
      "subscriptionPolicies": {
        "locationPlacementId": "Public_2014-09-01",
        "quotaId": "EnterpriseAgreement_2014-09-01",
        "spendingLimit": "Off"
      },
      "authorizationSource": "RoleBased"
    }
  ]
}



Name               : Default
Account            : [email protected]
Environment        : AzureCloud
Subscription       : ********-****-****-****-************
Tenant             : ********-****-****-****-************
TokenCache         : Microsoft.Azure.Commands.Common.Authentication.AuthenticationStoreTokenCache
VersionProfile     : 
ExtendedProperties : {}

DEBUG: AzureQoSEvent: CommandName - Set-AzureRmContext; IsSuccess - True; Duration - 00:00:01.7457943; Exception - ;
DEBUG: Finish sending metric.
DEBUG: 12:51:19 PM - SetAzureRMContextCommand end processing.
DEBUG: 12:51:19 PM - SetAzureRMContextCommand end processing.

Script/Steps for Reproduction

Login-AzureRmAccount
Save-AzureRmContext -Path .\profile.json
Import-AzureRmContext .\profile.json
Select-AzureRmSubscription -SubscriptionName Sandbox

> Selects correct subscription

Import-AzureRmContext .\profile.json
Select-AzureRmSubscription -SubscriptionName Sandbox

> Selects default subscription

tran-barry avatar Oct 04 '17 19:10 tran-barry

@tran-barry No repro with latest version., and you have excerpted all the data that would allow us to differentiate the subscriptions and tenants.

Can you provide a debug log ($DebugPreference="Continue") when you repro this issue? Also, can you try with the latest version?

Finally - is there a reason why you are using Import/Export instead of using Context AutoSave (which automatically saves the authentication state of Azure PowerShell, so that save/Import is unnecessary)

markcowl avatar Dec 08 '17 18:12 markcowl

I've just reproduced the problem with AzureRM V5.0.1. I can confirm that the problem does not exist in V4.3.1.

Here's my Debug Log: DebugLog.txt

I work at the same organization as @tran-barry. We have build scripts created even before azure-powershell V1.0 was a thing, and the patterns we used for authentication at that time are still in place. We just began the process of migrating to ContextAutoSave, but that has a dependency on upgrading azure-powershell from V4.3.1 to V4.4.0 and beyond. Unfortunately, this defect, which was introduced in V4.4.0 breaks our existing scripts.

So.. we have a chicken and egg problem. If we upgrade azure-powershell first, our buildscripts will fail, but if we upgrade our buildscripts first, they won't be compatible with version of azure-powershell on the build agents.

vicp-iq avatar Dec 08 '17 21:12 vicp-iq

Any update on this? We have some features in the pipe that depend on the Autosave logic, and we really want to launch them.

vicp-iq avatar Jan 29 '18 15:01 vicp-iq

Can somebody help me understand the priority on this? It is blocking my organization from moving forward with the Azure Context Autosave feature.

vicp-iq avatar Feb 26 '18 16:02 vicp-iq

I dug into why this is happening and I found that Import-AzureRmContext is the cmdlet that may have a bug in it.

Lets say the profile you're loading in has Subscription A (or Context A) saved in it. You load the profile using Import-AzureRmContext -Path ... and then call Get-AzureRmContext -ListAvailable, which outputs:

Name             : [[email protected], xxxxx-xxxxx-xxxxx-xxxxx-xxxx72c3b]
Account          : [email protected]
SubscriptionName : SubscriptionA
TenantId         : xxxxx-xxxxx-xxxxx-xxxxx-xxxxx
Environment      : AzureCloud

Name             : Default
Account          :
SubscriptionName :
TenantId         :
Environment      :

In the same session, you then select a different context:Select-AzureRmSubscription -SubscriptionName "SubscriptionB".

You now have this when you call Get-AzureRmContext -ListAvailable:

Name             : [[email protected], xxxxx-xxxxx-xxxxx-xxxxx-xxxx72c3b]
Account          : [email protected]
SubscriptionName : SubscriptionA
TenantId         : xxxxx-xxxxx-xxxxx-xxxxx-xxxxx
Environment      : AzureCloud

Name             : [[email protected], xxxxx-xxxxx-xxxxx-xxxxx-xxxxx3e5d6]
Account          : [email protected]
SubscriptionName : SubscriptionB
TenantId         : bxxxxx-xxxxx-xxxxx-xxxxx-xxxxx
Environment      : AzureCloud

Name             : Default
Account          :
SubscriptionName :
TenantId         :
Environment      :

if you reload your profile by calling Import-AzureRmContext -Path ... and then call Get-AzureRmContext -ListAvailable, you will see this:

Name             : [[email protected], xxxxx-xxxxx-xxxxx-xxxxx-xxxx72c3b]
Account          : [email protected]
SubscriptionName : SubscriptionA
TenantId         : xxxxx-xxxxx-xxxxx-xxxxx-xxxxx
Environment      : AzureCloud

Name             : [[email protected], xxxxx-xxxxx-xxxxx-xxxxx-xxxxx3e5d6]
Account          : 
SubscriptionName :
TenantId         : 
Environment      : 

Name             : Default
Account          :
SubscriptionName :
TenantId         :
Environment      :

SubscriptionB still exists as a context but most of the fields are null. I believe Select-AzureRmSubscription -SubscriptionName "SubscriptionB" does not know how to select Subscription B due to the null fields and therefore defaults back to the subscription it was previously on.

It appears that when you Import your context -> Select Subscription A -> Select Subscription C -> Select Subscription B -> Import context again

and then call Get-AzureRmContext -ListAvailable, it loads whatever contexts you had saved in your profile (Subscription A in this case), deletes the subscription C context, and then places Subscription B (the context you were currently on) in an invalid state by turning most of the object fields to null

I'm running the debugger on the code right now to figure out why it isn't clearing the context you were currently on prior to reloading the profile, but it's going slow because it's my first time diving into the azure-powershell code :-)

AMoghrabi avatar Apr 11 '18 05:04 AMoghrabi

I looked further and it looks like this commit and method call which was introduced in version 4.4.0 is causing the issue.

As I understand it, the method clears the current contexts loaded and tries to create a new AzureContext. During instantiation, it sets all of the values of the new AzureContext to null and assigns the key name to whatever DefaultContextKey is. Somewhere in the process of selecting a new context using Select-AzureRmSubscription, it sets the DefaultContextKey to the new context's key name.

That's why Import-AzureRmContext has this at the end of the cmdlet execution;

Name             : [[email protected], xxxxx-xxxxx-xxxxx-xxxxx-xxxxx3e5d6]
Account          : 
SubscriptionName :
TenantId         : 
Environment      : 

I'm looking into a fix now but I first need to understand why TryCopyProfile is being called.

In addition, the commit appears to have broken the -AzureContext parameter:

Import-AzureRmContext -AzureContext (Connect-AzureRmAccount)

Import-AzureRmContext : Collection was modified; enumeration operation may not execute.
At line:1 char:1
+ Import-AzureRmContext -AzureContext (Connect-AzureRmAccount)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : CloseError: (:) [Import-AzureRmContext], InvalidOperationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ImportAzureRMContextCommand

I'm looking into this error as well.

AMoghrabi avatar Apr 13 '18 06:04 AMoghrabi

https://github.com/Azure/azure-powershell/pull/5958

AMoghrabi avatar Apr 16 '18 04:04 AMoghrabi

I'm having the same issue in 5.7.0. Importing the context from JSON file, my 3 subscriptions seem ok. Then selecting the needed subscription with Set-AzureRMContext or its alias Select-AzureRMSubscription, and I've tried all parameter sets (by name, id or object). In all cases, first call succeeds (selecting the right subscription), but second and subsequent calls fail (always leaving in the default subscription). When it fails, looping the call to try again Set-AzureRMContext will not change anything.

juancrl avatar Apr 30 '18 09:04 juancrl

+1 I have a similar issue (I think)

I load my profile using Select-AzureRmProfile and then do a Select-AzureRmSubscription and it will intermittently either select the subscription I give it or give me the default subscription for my account (which is different to the sbuscription ID I pass to Select-AzureRmSubscription.

I'm on version 5.1.1 of the commandlets.

robdmoore avatar May 10 '18 01:05 robdmoore

I've got it working by now.

With AzureRM 5.7.0 and probably 5.x -> you have to provide BOTH parameters to Select-AzureRMProfile (Set-AzureRMContext, better use the cmdlet, not the alias). SubscriptionID and SubscriptionName. Only SubscriptionID DOES NOT CHANGE THE CONTEXT NOR GIVES AN ERROR. Be careful, as they have changed the parameter names, -SubscriptionID and -SubscriptionName are ALIAS PARAMETERS for the same -Subscription param. So you have to Set-AzureRMContext -Subscription $SubsID -NAME $SubsName (which is different to all examples and documentation you can find on the web)

While testing this, AzureRM 6.0.0 and 6.0.1 were published. I've tested 6.0.1 and everything on my code seems to work, and it seems the expected behaviour (Set-AzureRMContext -Subscription $subsID) is working... but test it exhaustively !

My recommendation : Update-Module to 6.0.1 or better !! (And always test carefully, I'm sure they'll screw up more parameters)

juancrl avatar May 10 '18 07:05 juancrl

This has been verified to be fixed as of AzureRM 6. See the discussion as part of the PR that has a potential fix, but is no longer needed: https://github.com/Azure/azure-powershell/pull/5958#pullrequestreview-132241298

MiYanni avatar Jun 27 '18 17:06 MiYanni