AADSTS50020: User account '{EmailHidden}' from identity provider does not exist in tenant 'Microsoft Services' and cannot access the application - azure-keyvault

Using Azure.Identity Running dotnet 6.0.302 On Windows 10 Visual Studio 2022 v17.1.5 App Type - Asp.Net Core Web Api
I am trying to implement Azure App Configuration.
While using DefaultCredentials() the attempt to obtain an authentication token fails at all levels of credential types. I tried providing a user assigned managed identity but no avail.
I notice something fishy in the logs though. there are instances of Azure.RequestFailedException: A socket operation was attempted to an unreachable network. (169.254.169.254:80) but i am not sure what the ip address refers to.
Please Note:-
I could not ping this ip address from my PC.
The error is same irrespective of using a Managed Identity. So using just new DefaultAzureCredential() without any parameters also throws the same error.
I am using my personal Azure Subscription.
Kindly provide guidance to solve this issue and move forward.
Here is my WebApi configuration
var builder = WebApplication.CreateBuilder(args);
// Setup a listener to monitor logged events.
using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger();
var defaultClientCredentialsOptions = new DefaultAzureCredentialOptions()
{
Diagnostics =
{
LoggedHeaderNames = { "x-ms-request-id" },
LoggedQueryParameters = { "api-version" },
IsLoggingContentEnabled = true
}
};
// Plugin App Configuration Store
var appConfigStore = builder.Configuration.GetConnectionString("EshopClone:AppConfiguration");
var userAssignedMIClientId = builder.Configuration["UserAssignedMIClientId"];
var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = userAssignedMIClientId });
builder.Host.ConfigureAppConfiguration(hostBuilder =>
{
hostBuilder.AddAzureAppConfiguration(options =>
{
options.Connect(appConfigStore)
.ConfigureKeyVault(kv =>
{
kv.SetCredential(credential);
});
});
});
Here is the detailed error:
EshopClone\Services\Catalog\Catalog.Api\bin\Debug\net6.0\Catalog.Api.exe (process 38972) exited with code -1.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .
EshopClone\Services\Catalog\Catalog.Api\bin\Debug\net6.0\Catalog.Api.exe (process 43516) exited with code -1.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .[Informational] Azure-Core: Request [2a2c1a3c-7c03-4ccf-b529-82ebe89b1db0] GET https://myappconfigurationurl.azconfig.io/kv/?key=REDACTED&label=REDACTED&api-version=1.0
Accept:application/vnd.microsoft.appconfig.kv+json
Correlation-Context:REDACTED
User-Agent:Microsoft.Extensions.Configuration.AzureAppConfiguration/5.1.0,azsdk-net-Data.AppConfiguration/1.2.0,(.NET 6.0.7; Microsoft Windows 10.0.19044)
x-ms-client-request-id:2a2c1a3c-7c03-4ccf-b529-82ebe89b1db0
x-ms-return-client-request-id:true
x-ms-content-sha256:REDACTED
Date:Sun, 31 Jul 2022 01:22:01 GMT
Authorization:REDACTED
client assembly: Azure.Data.AppConfiguration
[Informational] Azure-Core: Response [2a2c1a3c-7c03-4ccf-b529-82ebe89b1db0] 200 OK (01.1s)
Server:openresty/1.17.8.2
Date:Sun, 31 Jul 2022 01:22:14 GMT
Transfer-Encoding:chunked
Connection:keep-alive
Sync-Token:zAJw6V16=NToxOSMxOTk0ODMyOA==;sn=19948328
x-ms-request-id:a969b01a-edd4-4b14-b38f-c37c0aee185f
x-ms-client-request-id:2a2c1a3c-7c03-4ccf-b529-82ebe89b1db0
x-ms-correlation-request-id:a969b01a-edd4-4b14-b38f-c37c0aee185f
Access-Control-Allow-Origin:*
Access-Control-Allow-Credentials:true
Access-Control-Expose-Headers:REDACTED
Strict-Transport-Security:max-age=15724800; includeSubDomains
Content-Type:application/vnd.microsoft.appconfig.kvset+json; charset=utf-8
[Informational] Azure-Core: Request [7b3aebb0-5882-41fd-8c4c-3f2cb359ef15] GET https://mykeyvault.vault.azure.net/secrets/Catalog-Api-KVMessage/?api-version=7.2
Accept:application/json
x-ms-client-request-id:7b3aebb0-5882-41fd-8c4c-3f2cb359ef15
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Security.KeyVault.Secrets/4.2.0,(.NET 6.0.7; Microsoft Windows 10.0.19044)
Content-Type:application/json
client assembly: Azure.Security.KeyVault.Secrets
[Warning] Azure-Core: Error response [7b3aebb0-5882-41fd-8c4c-3f2cb359ef15] 401 Unauthorized (00.2s)
Cache-Control:no-cache
Pragma:no-cache
WWW-Authenticate:Bearer authorization="https://login.windows.net/8f75f741-333d-429e-a535-e1304c1dd62d", resource="https://vault.azure.net"
x-ms-keyvault-region:eastus
x-ms-client-request-id:7b3aebb0-5882-41fd-8c4c-3f2cb359ef15
x-ms-request-id:fa78180c-6723-4459-a182-ca2decfecaad
x-ms-keyvault-service-version:1.9.472.5
x-ms-keyvault-network-info:conn_type=Ipv4;addr=76.205.200.211;act_addr_fam=InterNetwork;
X-Content-Type-Options:REDACTED
Strict-Transport-Security:REDACTED
Date:Sun, 31 Jul 2022 01:22:14 GMT
Content-Length:97
Content-Type:application/json; charset=utf-8
Expires:-1
[Informational] Azure-Identity: DefaultAzureCredential.GetToken invoked. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15
[Informational] Azure-Identity: EnvironmentCredential.GetToken invoked. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15
[Informational] Azure-Identity: EnvironmentCredential.GetToken was unable to retrieve an access token. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15 Exception: Azure.Identity.CredentialUnavailableException (0x80131500): EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot
[Informational] Azure-Identity: ManagedIdentityCredential.GetToken invoked. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15
[Informational] Azure-Core: Request [5fb9375f-1c4c-40b6-9ecc-ee29f260e34b] GET http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=REDACTED&client_id=REDACTED
Metadata:REDACTED
x-ms-client-request-id:5fb9375f-1c4c-40b6-9ecc-ee29f260e34b
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.6.0,(.NET 6.0.7; Microsoft Windows 10.0.19044)
client assembly: Azure.Identity
[Informational] Azure-Core: Request [5fb9375f-1c4c-40b6-9ecc-ee29f260e34b] exception Azure.RequestFailedException: A socket operation was attempted to an unreachable network. (169.254.169.254:80)
---> System.Net.Http.HttpRequestException: A socket operation was attempted to an unreachable network. (169.254.169.254:80)
---> System.Net.Sockets.SocketException (10051): A socket operation was attempted to an unreachable network.
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)
at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Azure.Core.Pipeline.HttpClientTransport.ProcessAsync(HttpMessage message, Boolean async)
--- End of inner exception stack trace ---
at Azure.Core.Pipeline.HttpClientTransport.ProcessAsync(HttpMessage message, Boolean async)
at Azure.Core.Pipeline.HttpPipelineTransportPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline)
at Azure.Core.Pipeline.ResponseBodyPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async) at Azure.Core.Pipeline.LoggingPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
[Informational] Azure-Core: Request [5fb9375f-1c4c-40b6-9ecc-ee29f260e34b] retry number 1 took 00.1s
[Informational] Azure-Core: Request [5fb9375f-1c4c-40b6-9ecc-ee29f260e34b] GET http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=REDACTED&client_id=REDACTED
Metadata:REDACTED
x-ms-client-request-id:5fb9375f-1c4c-40b6-9ecc-ee29f260e34b
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.6.0,(.NET 6.0.7; Microsoft Windows 10.0.19044)
client assembly: Azure.Identity
[Informational] Azure-Core: Request [5fb9375f-1c4c-40b6-9ecc-ee29f260e34b] exception Azure.RequestFailedException: A socket operation was attempted to an unreachable network. (169.254.169.254:80)
---> System.Net.Http.HttpRequestException: A socket operation was attempted to an unreachable network. (169.254.169.254:80)
---> System.Net.Sockets.SocketException (10051): A socket operation was attempted to an unreachable network.
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)
at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Azure.Core.Pipeline.HttpClientTransport.ProcessAsync(HttpMessage message, Boolean async)
--- End of inner exception stack trace ---
at Azure.Core.Pipeline.HttpClientTransport.ProcessAsync(HttpMessage message, Boolean async)
at Azure.Core.Pipeline.HttpPipelineTransportPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline)
at Azure.Core.Pipeline.ResponseBodyPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async) at Azure.Core.Pipeline.LoggingPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
[Informational] Azure-Core: Request [5fb9375f-1c4c-40b6-9ecc-ee29f260e34b] retry number 2 took 00.0s
[Informational] Azure-Core: Request [5fb9375f-1c4c-40b6-9ecc-ee29f260e34b] GET http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=REDACTED&client_id=REDACTED
Metadata:REDACTED
x-ms-client-request-id:5fb9375f-1c4c-40b6-9ecc-ee29f260e34b
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.6.0,(.NET 6.0.7; Microsoft Windows 10.0.19044)
client assembly: Azure.Identity
[Informational] Azure-Core: Request [5fb9375f-1c4c-40b6-9ecc-ee29f260e34b] exception Azure.RequestFailedException: A socket operation was attempted to an unreachable network. (169.254.169.254:80)
---> System.Net.Http.HttpRequestException: A socket operation was attempted to an unreachable network. (169.254.169.254:80)
---> System.Net.Sockets.SocketException (10051): A socket operation was attempted to an unreachable network.
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)
at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Azure.Core.Pipeline.HttpClientTransport.ProcessAsync(HttpMessage message, Boolean async)
--- End of inner exception stack trace ---
at Azure.Core.Pipeline.HttpClientTransport.ProcessAsync(HttpMessage message, Boolean async)
at Azure.Core.Pipeline.HttpPipelineTransportPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline)
at Azure.Core.Pipeline.ResponseBodyPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async) at Azure.Core.Pipeline.LoggingPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
[Informational] Azure-Core: Request [5fb9375f-1c4c-40b6-9ecc-ee29f260e34b] retry number 3 took 00.0s
[Informational] Azure-Core: Request [5fb9375f-1c4c-40b6-9ecc-ee29f260e34b] GET http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=REDACTED&client_id=REDACTED
Metadata:REDACTED
x-ms-client-request-id:5fb9375f-1c4c-40b6-9ecc-ee29f260e34b
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.6.0,(.NET 6.0.7; Microsoft Windows 10.0.19044)
client assembly: Azure.Identity
[Informational] Azure-Core: Request [5fb9375f-1c4c-40b6-9ecc-ee29f260e34b] exception Azure.RequestFailedException: A socket operation was attempted to an unreachable network. (169.254.169.254:80)
---> System.Net.Http.HttpRequestException: A socket operation was attempted to an unreachable network. (169.254.169.254:80)
---> System.Net.Sockets.SocketException (10051): A socket operation was attempted to an unreachable network.
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)
at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Azure.Core.Pipeline.HttpClientTransport.ProcessAsync(HttpMessage message, Boolean async)
--- End of inner exception stack trace ---
at Azure.Core.Pipeline.HttpClientTransport.ProcessAsync(HttpMessage message, Boolean async)
at Azure.Core.Pipeline.HttpPipelineTransportPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline)
at Azure.Core.Pipeline.ResponseBodyPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async) at Azure.Core.Pipeline.LoggingPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
[Informational] Azure-Identity: ManagedIdentityCredential.GetToken was unable to retrieve an access token. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15 Exception: Azure.Identity.CredentialUnavailableException (0x80131500): ManagedIdentityCredential authentication unavailable. Multiple attempts failed to obtain a token from the managed identity endpoint.
---> System.AggregateException (0x80131500): Retry failed after 4 tries. Retry settings can be adjusted in ClientOptions.Retry. (A socket operation was attempted to an unreachable network. (169.254.169.254:80)) (A socket operation was attempted to an unreachable network. (169.254.169.254:80)) (A socket operation was attempted to an unreachable network. (169.254.169.254:80)) (A socket operation was attempted to an unreachable network. (169.254.169.254:80))
---> Azure.RequestFailedException (0x80131500): A socket operation was attempted to an unreachable network. (169.254.169.254:80)
---> System.Net.Http.HttpRequestException (0x80004005): A socket operation was attempted to an unreachable network. (169.254.169.254:80)
---> System.Net.Sockets.SocketException (0x80004005): A socket operation was attempted to an unreachable network.
[Informational] Azure-Identity: VisualStudioCredential.GetToken invoked. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15
[Informational] Azure-Identity: VisualStudioCredential.GetToken was unable to retrieve an access token. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15 Exception: Azure.Identity.CredentialUnavailableException (0x80131500): Process "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\Asal\TokenService\Microsoft.Asal.TokenService.exe" has failed with unexpected error: TS003: Error, TS004: Unable to get access token. 'AADSTS50020: User account '{EmailHidden}' from identity provider 'live.com' does not exist in tenant 'Microsoft Services' and cannot access the application '872cd9fa-d31f-45e0-9eab-6e460a02d1f1'(Visual Studio) in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.
Trace ID: 72758044-988d-4eb7-a02a-88b03cc98b00
Correlation ID: 9ab458cd-36b1-4fcb-b9c5-a6fda19b3704
Timestamp: 2022-07-31 01:22:23Z'.
---> System.InvalidOperationException (0x80131509): TS003: Error, TS004: Unable to get access token. 'AADSTS50020: User account '{EmailHidden}' from identity provider 'live.com' does not exist in tenant 'Microsoft Services' and cannot access the application '872cd9fa-d31f-45e0-9eab-6e460a02d1f1'(Visual Studio) in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.
Trace ID: 72758044-988d-4eb7-a02a-88b03cc98b00
Correlation ID: 9ab458cd-36b1-4fcb-b9c5-a6fda19b3704
Timestamp: 2022-07-31 01:22:23Z'
[Informational] Azure-Identity: VisualStudioCodeCredential.GetToken invoked. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15
[Informational] Azure-Identity: VisualStudioCodeCredential.GetToken was unable to retrieve an access token. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15 Exception: Azure.Identity.CredentialUnavailableException (0x80131500): Stored credentials not found. Need to authenticate user in VSCode Azure Account. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/vscodecredential/troubleshoot
---> System.InvalidOperationException (0x80131509): CredRead has failed but error is unknown.
[Informational] Azure-Identity: AzureCliCredential.GetToken invoked. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15
[Informational] Azure-Identity: AzureCliCredential.GetToken was unable to retrieve an access token. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15 Exception: Azure.Identity.CredentialUnavailableException (0x80131500): Azure CLI not installed
[Informational] Azure-Identity: AzurePowerShellCredential.GetToken invoked. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15
[Informational] Azure-Identity: AzurePowerShellCredential.GetToken was unable to retrieve an access token. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15 Exception: Azure.Identity.CredentialUnavailableException (0x80131500): Az.Account module >= 2.2.0 is not installed.
[Informational] Azure-Identity: DefaultAzureCredential.GetToken was unable to retrieve an access token. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: 7b3aebb0-5882-41fd-8c4c-3f2cb359ef15 Exception: Azure.Identity.CredentialUnavailableException (0x80131500): DefaultAzureCredential failed to retrieve a token from the included credentials. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/defaultazurecredential/troubleshoot
- EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot
- ManagedIdentityCredential authentication unavailable. Multiple attempts failed to obtain a token from the managed identity endpoint.
- Process "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\Asal\TokenService\Microsoft.Asal.TokenService.exe" has failed with unexpected error: TS003: Error, TS004: Unable to get access token. 'AADSTS50020: User account '{EmailHidden}' from identity provider 'live.com' does not exist in tenant 'Microsoft Services' and cannot access the application '872cd9fa-d31f-45e0-9eab-6e460a02d1f1'(Visual Studio) in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.
Trace ID: 72758044-988d-4eb7-a02a-88b03cc98b00
Correlation ID: 9ab458cd-36b1-4fcb-b9c5-a6fda19b3704
Timestamp: 2022-07-31 01:22:23Z'.
- Stored credentials not found. Need to authenticate user in VSCode Azure Account. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/vscodecredential/troubleshoot
- Azure CLI not installed
- Az.Account module >= 2.2.0 is not installed.
---> System.AggregateException (0x80131500): Multiple exceptions were encountered while attempting to authenticate. (EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot) (ManagedIdentityCredential authentication unavailable. Multiple attempts failed to obtain a token from the managed identity endpoint.) (Process "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\Asal\TokenService\Microsoft.Asal.TokenService.exe" has failed with unexpected error: TS003: Error, TS004: Unable to get access token. 'AADSTS50020: User account '{EmailHidden}' from identity provider 'live.com' does not exist in tenant 'Microsoft Services' and cannot access the application '872cd9fa-d31f-45e0-9eab-6e460a02d1f1'(Visual Studio) in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.
Trace ID: 72758044-988d-4eb7-a02a-88b03cc98b00
Correlation ID: 9ab458cd-36b1-4fcb-b9c5-a6fda19b3704
Timestamp: 2022-07-31 01:22:23Z'.) (Stored credentials not found. Need to authenticate user in VSCode Azure Account. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/vscodecredential/troubleshoot) (Azure CLI not installed) (Az.Account module >= 2.2.0 is not installed.)
---> Azure.Identity.CredentialUnavailableException (0x80131500): EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot
EshopClone\Services\Catalog\Catalog.Api\bin\Debug\net6.0\Catalog.Api.exe (process 45532) exited with code -1.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .

All the exceptions including RequestFailedExcpetion ,AADSTS50020 (which are often caused by the DefaultAzureCredential authenticating an account other than the intended one or when that account does not have the correct permissions or roles assigned.) etc leads to saying User being Unauthorized to call that particular endpoint where your target might be on a different network for that endpoint which is leading to socket exception .
Please check following ways that can resolve the issue.
Sign out and sign in VS again. select Tools > Options menu to launch the Options dialog In Visual Studio.
Navigate to the Azure Service Authentication options and sign in with your Azure Active Directory required account.
To try and get the right account to access, try using AzureCli, loggin
into that one account and sign out of your others or with VS, make
sure that the tokens are only being requested from that one account
and not any other
use the below cli command account to verify the account which is
currently logged in but before that please ensure the Azure CLI is
properly installed. Installation instructions can be found here.
az account show
Once you've verified the Azure CLI is using correct account, you can
validate that it’s able to obtain tokens for this account.
az account get-access-token --output json --resource https://management.core.windows.net
Update Visual Studio and packages to the latest version.
excluding the credential with the ExcludeXXXCredential property
Please Note that credentials such as the
InteractiveBrowserCredential are not included by default which
requires user interaction. You may have to enable or disable
required credentials this when constructing the
DefaultAzureCredential by setting for example:the
includeInteractiveCredentials to true, or the
ExcludeInteractiveBrowserCredential property to false in
DefaultAzureCredentialOptions.
Try by giving ExcludeVisualStudioCredential to true if above steps
doesnt resolve the issue .Or you can include azurecli credential or
others to for user authentication .
var options = new DefaultAzureCredentialOptions()
{
ExcludeAzurePowerShellCredential = true,
ExcludeEnvironmentCredential = true,
ExcludeAzureCliCredential = true,
ExcludeInteractiveBrowserCredential = false,
ExcludeManagedIdentityCredential = true,
ExcludeSharedTokenCacheCredential = true,
ExcludeVisualStudioCodeCredential = true,
ExcludeVisualStudioCredential = false
};
var cred = new DefaultAzureCredential(options);
Please ensure that the correct role is assigned to the account being
used specific to that service rather than overall subscription role
such as owner for subscription
Ensure that relevant environment variables are set prior to
application
• To authenticate a service principal which is using a
client secret, ensure the variables AZURE_CLIENT_ID, AZURE_TENANT_ID and AZURE_CLIENT_SECRET are properly set .
• And
for managed identity for App Service make sure it is configured
properly and environment variables like MSI_ENDPOINT and
MSI_SECRET have been set in the environment. Instructions can be
found here.
Please check Troubleshooting· GitHub
References:
azure sdk for net issues.github
Configure managed identities with Azure App Configuration |
Microsoft Docs

Your code uses a connection string to connect to Azure App Configuration and uses AAD (user-assigned managed identity) to connect to Key Vault (for Key Vault references). The problem is not with Azure App Configuration but with the Key Vault. Please make sure you granted your user-assigned managed identity the read permission to the secrets in your Key Vault.
Please check out the Grant your app access to Key Vault in the doc below:
https://learn.microsoft.com/azure/azure-app-configuration/use-key-vault-references-dotnet-core?tabs=core5x#grant-your-app-access-to-key-vault

You need to provide the correct TenantId for Visual Studio authentication:
new DefaultAzureCredential(new DefaultAzureCredentialOptions { VisualStudioTenantId = "<your_tenant_id>" })
The related part of your error log is:
Process "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\Asal\TokenService\Microsoft.Asal.TokenService.exe" has failed with unexpected error: TS003: Error, TS004: Unable to get access token. 'AADSTS50020: User account '{EmailHidden}' from identity provider 'live.com' does not exist in tenant 'Microsoft Services' and cannot access the application '872cd9fa-d31f-45e0-9eab-6e460a02d1f1'(Visual Studio) in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.

Related

Ocelot certificate problem. The SSL connection could not be established, see inner exception

I am running in Local using Docker an Ocelot API gateway (https://localhost:5010) service that calls a Dot net core API (https://localhost:5003).
I used self signed certificates and both services are secure:
To make it work locally I add in Ocelot.Development.json:
"DownstreamPathTemplate": "/ActivityTypes",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "xplora.api",
"Port": "443"
}
],
"UpstreamPathTemplate": "/ActivityTypes",
"UpstreamHttpMethod": [ "GET" ],
"RateLimitOptions": {
"ClientWhitelist": [],
"EnableRateLimiting": true,
"Period": "3s",
"PeriodTimespan": 1,
"Limit": 1
},
"FileCacheOptions": { "TtlSeconds": 30 }
}
Where xplora.api is the name of the container defined in docker-compose.
container_name: xplora.api
environment:
When I access the Ocelot api gateway I get this error:
xploraproject-xploraapigateway-1 | requestId: 0HMDG3PCRH54C:00000001, previousRequestId: no previous request id, message: Error Code: ConnectionToDownstreamServiceError Message: Error connecting to downstream service, exception: System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
xploraproject-xploraapigateway-1 | ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch, RemoteCertificateChainErrors
xploraproject-xploraapigateway-1 | at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)
xploraproject-xploraapigateway-1 | at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)
xploraproject-xploraapigateway-1 | at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
xploraproject-xploraapigateway-1 | --- End of inner exception stack trace ---
xploraproject-xploraapigateway-1 | at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
I suspect the problem is that when I try to access this services using localhost it works fine because the certificate is assigned to localhost domain but when Ocelot tries to use https://xplora.api:5003 this certificate is not working. Am I right? If so.. how can I make it work? I used "DangerousAcceptAnyServerCertificateValidator": true in Ocelot.Development.json and it works but I want a real solution, without using DangerousAcceptAnyServerCertificateValidator.
Thanks

httpClient.SendAsync throws Unspecified GSS failure

I am using .NET Core 3.1
Here is a code that I am using:
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(URL), "NEGOTIATE", new NetworkCredential(USER, PASSWORD, DOMAIN));
using (HttpClientHandler handler = new HttpClientHandler())
{
handler.Credentials = credentialCache;
using (HttpClient httpClient = new HttpClient(handler))
{
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("GET"), REQUEST_URL);
HttpResponseMessage response = httpClient.SendAsync(request).Result;
Console.Write(response.ToString());
}
}
It works corrent on my windows machine but crushes when is launched on linux docker container:
System.AggregateException: One or more errors occurred. (GSSAPI operation failed with error - Unspecified GSS failure. Minor code may provide more information (Cannot find KDC for realm "DOMAIN_NAME").)
---> System.ComponentModel.Win32Exception (0x80090020): GSSAPI operation failed with error - Unspecified GSS failure. Minor code may provide more information(Cannot find KDC for realm "DOMAIN_NAME").
at System.Net.Security.NegotiateStreamPal.AcquireCredentialsHandle(String package, Boolean isServer, NetworkCredential credential)
at System.Net.NTAuthentication.Initialize(Boolean isServer, String package, NetworkCredential credential, String spn, ContextFlagsPal requestedContextFlags,ChannelBinding channelBinding)
at System.Net.Http.AuthenticationHelper.SendWithNtAuthAsync(HttpRequestMessage request, Uri authUri, ICredentials credentials, Boolean isProxyAuth, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.AuthenticationHelper.SendWithAuthAsync(HttpRequestMessage request, Uri authUri, ICredentials credentials, Boolean preAuthenticate, Boolean isProxyAuth, Boolean doRequestAuth, HttpConnectionPool pool, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at OurHomeServer.Log.LoggingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in /src/OurHomeServer/Log/LoggingHandler.cs:line 35
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
It works when I use curl request in container's shell.
I added following line to my Dockerfile
RUN apt install -y mc sudo syslog-ng realmd gss-ntlmssp
and now it works!!

How do I resolve Kestrel/HTTPS Error for ASP.NET MVC Core 2.2?

I am trying to run an ASP.NET MVC Web app on a mac via visual studio code and getting the following error:-
Using launch settings from '/Users/dhumes/development/aspnetdev/aspnetwebapp/Properties/launchSettings.json' [Profile 'aspnetwebapp']...
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using '/Users/dhumes/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
crit: Microsoft.AspNetCore.Server.Kestrel[0]
Unable to start Kestrel.
System.InvalidOperationException: Unable to configure HTTPS endpoint. No server certificate was specified, and the default developer certificate could not be found.
To generate a developer certificate run 'dotnet dev-certs https'. To trust the certificate (Windows and macOS only) run 'dotnet dev-certs https --trust'.
For more information on configuring HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.
at Microsoft.AspNetCore.Hosting.ListenOptionsHttpsExtensions.UseHttps(ListenOptions listenOptions, Action1 configureOptions)
at Microsoft.AspNetCore.Hosting.ListenOptionsHttpsExtensions.UseHttps(ListenOptions listenOptions)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.BindAsync(AddressBindContext context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindAsync(IServerAddressesFeature addresses, KestrelServerOptions serverOptions, ILogger logger, Func2 createBinding)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.StartAsync[TContext](IHttpApplication1 application, CancellationToken cancellationToken)
Unhandled Exception: System.InvalidOperationException: Unable to configure HTTPS endpoint. No server certificate was specified, and the default developer certificate could not be found.
To generate a developer certificate run 'dotnet dev-certs https'. To trust the certificate (Windows and macOS only) run 'dotnet dev-certs https --trust'.
For more information on configuring HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.
at Microsoft.AspNetCore.Hosting.ListenOptionsHttpsExtensions.UseHttps(ListenOptions listenOptions, Action1 configureOptions)
at Microsoft.AspNetCore.Hosting.ListenOptionsHttpsExtensions.UseHttps(ListenOptions listenOptions)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.BindAsync(AddressBindContext context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindAsync(IServerAddressesFeature addresses, KestrelServerOptions serverOptions, ILogger logger, Func2 createBinding)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.StartAsync[TContext](IHttpApplication1 application, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.StartAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String shutdownMessage)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
at aspnetwebapp.Program.Main(String[] args) in /Users/dhumes/development/aspnetdev/aspnetwebapp/Program.cs:line 17
Try running
dotnet dev-certs https --trust
This will install a local certificate for localhost.

identity server 4 and Ocelot integration With Docker

I am trying to integrate Ocelot API gateway with ID4. As per Ocelot documentation we can validate token with external id server https://whereyouridentityserverlives.com, Now, i'm integrating ID server and GateWay in same docker compose,
gateway:
image: ${DOCKER_REGISTRY}gateway
build:
context: .
dockerfile: GateWay/Dockerfile
depends_on:
- identityserver
links:
- identityserver
networks:
- api_backend
identityserver:
image: ${DOCKER_REGISTRY}identityserver:dev
networks:
- api_backend
networks:
api_backend:
driver: "bridge"
and in my gateway, I am configuring like
ConfigureServices(s => {
s.AddAuthentication()
.AddIdentityServerAuthentication("TestKey", o =>
{
o.Authority = "https://identityserver";
o.ApiName = "api1";
o.SupportedTokens = SupportedTokens.Both;
});
Everything works upto this, Now at the time of token validation it is getting error, No such device or address
Most likely, gateway server is not able to connect id4, and hence not able to get the discovery document.
Relevant parts of the log file
Request starting HTTP/1.1 GET https://localhost:44326/b
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET https://localhost:44326/b
Ocelot.Errors.Middleware.ExceptionHandlerMiddleware:Debug: requestId: 0HLF9AEP1C9GQ:00000001, previousRequestId: no previous request id, message: ocelot pipeline started
[40m[37mdbug[39m[22m[49m: Ocelot.Errors.Middleware.ExceptionHandlerMiddleware[0]
requestId: 0HLF9AEP1C9GQ:00000001, previousRequestId: no previous request id, message: ocelot pipeline started
Ocelot.DownstreamRouteFinder.Middleware.DownstreamRouteFinderMiddleware:Debug: requestId: 0HLF9AEP1C9GQ:00000001, previousRequestId: no previous request id, message: Upstream url path is /b
Ocelot.DownstreamRouteFinder.Middleware.DownstreamRouteFinderMiddleware:Debug: requestId: 0HLF9AEP1C9GQ:00000001, previousRequestId: no previous request id, message: downstream templates are /api/values
[40m[37mdbug[39m[22m[49m: Ocelot.DownstreamRouteFinder.Middleware.DownstreamRouteFinderMiddleware[0]
requestId: 0HLF9AEP1C9GQ:00000001, previousRequestId: no previous request id, message: Upstream url path is /b
[40m[37mdbug[39m[22m[49m: Ocelot.DownstreamRouteFinder.Middleware.DownstreamRouteFinderMiddleware[0]
requestId: 0HLF9AEP1C9GQ:00000001, previousRequestId: no previous request id, message: downstream templates are /api/values
[40m[32minfo[39m[22m[49m: Ocelot.RateLimit.Middleware.ClientRateLimitMiddleware[0]
requestId: 0HLF9AEP1C9GQ:00000001, previousRequestId: no previous request id, message: EndpointRateLimiting is not enabled for /api/values
Ocelot.RateLimit.Middleware.ClientRateLimitMiddleware:Information: requestId: 0HLF9AEP1C9GQ:00000001, previousRequestId: no previous request id, message: EndpointRateLimiting is not enabled for /api/values
[40m[32minfo[39m[22m[49m: Ocelot.Authentication.Middleware.AuthenticationMiddleware[0]
requestId: 0HLF9AEP1C9GQ:00000001, previousRequestId: no previous request id, message: /b is an authenticated route. AuthenticationMiddleware checking if client is authenticated
Ocelot.Authentication.Middleware.AuthenticationMiddleware:Information: requestId: 0HLF9AEP1C9GQ:00000001, previousRequestId: no previous request id, message: /b is an authenticated route. AuthenticationMiddleware checking if client is authenticated
The thread 422 has exited with code 0 (0x0).
The thread 435 has exited with code 0 (0x0).
[41m[30mfail[39m[22m[49m: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3]
Exception occurred while processing message.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: '[PII is hidden by default. Set the 'ShowPII' flag in IdentityModelEventSource.cs to true to reveal it.]'. ---> System.IO.IOException: IDX20804: Unable to retrieve document from: '[PII is hidden by default. Set the 'ShowPII' flag in IdentityModelEventSource.cs to true to reveal it.]'. ---> System.Net.Http.HttpRequestException: No such device or address ---> System.Net.Sockets.SocketException: No such device or address
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask`1 creationTask)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Error: Exception occurred while processing message.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: '[PII is hidden by default. Set the 'ShowPII' flag in IdentityModelEventSource.cs to true to reveal it.]'. ---> System.IO.IOException: IDX20804: Unable to retrieve document from: '[PII is hidden by default. Set the 'ShowPII' flag in IdentityModelEventSource.cs to true to reveal it.]'. ---> System.Net.Http.HttpRequestException: No such device or address ---> System.Net.Sockets.SocketException: No such device or address
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask`1 creationTask)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
What am I missing?

TFS vNext build agent fails with 407 proxy authentication error

Triggering a build from Visual Studio Team Services on an on-premise vNext build agent fails at the point of getting sources from the repo, presumably because of a corporate proxy.
The build log on VSTS shows:
2016-01-28T12:35:03.7688078Z Syncing repository: MyProject (TFVC)
2016-01-28T12:35:03.7688078Z workspaceName=ws_3_3
2016-01-28T12:35:05.0730362Z ##[error]HTTP code 407: Proxy Authentication Required
2016-01-28T12:35:05.3257849Z ##[error]Prepare repository failed with exception.
On the build server the agent log shows the following exception:
16:17:14.895983 System.AggregateException: One or more errors occurred. ---> Microsoft.TeamFoundation.DistributedTask.Agent.Common.AgentExecutionTerminationException: Prepare repository failed with exception. ---> Microsoft.TeamFoundation.TeamFoundationServiceUnavailableException: HTTP code 407: Proxy Authentication Required ---> System.Net.WebException: The remote server returned an error: (407) Proxy Authentication Required.
16:17:14.895983 at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
16:17:14.895983 at System.Net.HttpWebRequest.GetRequestStream()
16:17:14.895983 at Microsoft.TeamFoundation.Client.Channels.TfsHttpWebRequest.SendRequestAndGetResponse(HttpWebRequest webRequest, WebException& webException)
16:17:14.895983 --- End of inner exception stack trace ---
16:17:14.895983 at Microsoft.TeamFoundation.Client.Channels.TfsHttpWebRequest.ReadResponse(HttpWebResponse webResponse, WebException webException)
16:17:14.895983 at Microsoft.TeamFoundation.Client.Channels.TfsHttpWebRequest.IsAuthenticationChallenge(TfsMessage requestMessage, HttpWebResponse webResponse, WebException webException, TfsMessage& responseMessage)
16:17:14.895983 at Microsoft.TeamFoundation.Client.Channels.TfsHttpWebRequest.SendRequest()
16:17:14.895983 at Microsoft.TeamFoundation.Client.Channels.TfsHttpRequestChannel.Request(TfsMessage message, TimeSpan timeout)
16:17:14.895983 at Microsoft.TeamFoundation.Client.Channels.TfsHttpClientBase.Invoke(TfsClientOperation operation, Object[] parameters, TimeSpan timeout, Object[]& outputs)
16:17:14.895983 at Microsoft.TeamFoundation.Framework.Client.LocationWebService.Connect(Int32 connectOptions, Int32 lastChangeId, Int32 features)
16:17:14.895983 at Microsoft.TeamFoundation.Framework.Client.FrameworkServerDataProvider.Connect(ConnectOptions connectOptions)
16:17:14.895983 at Microsoft.TeamFoundation.Framework.Client.FrameworkServerDataProvider.EnsureConnected(ConnectOptions optionsNeeded)
16:17:14.895983 at Microsoft.TeamFoundation.Framework.Client.FrameworkServerDataProvider.get_AuthorizedIdentity()
16:17:14.895983 at Microsoft.TeamFoundation.VersionControl.Client.Client.ResolveUserUniqueName(String user)
16:17:14.895983 at Microsoft.TeamFoundation.VersionControl.Client.Client.GetLocalWorkspace(String workspaceName, String workspaceOwner)
16:17:14.895983 at Microsoft.TeamFoundation.DistributedTask.Task.Internal.Core.TfvcHelper.SyncRepository(VersionControlServer server, Uri repositoryUrl, String workspaceName, String rootPath, WorkingFolder[] workingFolders, String sourceVersion, Boolean cleanRepository, String shelveset, CancellationToken cancellationToken)
16:17:14.895983 at Microsoft.TeamFoundation.DistributedTask.Task.Internal.Core.TfvcHelper.Sync(ITaskEndpoint endpoint, String localPath, Dictionary`2 serverPathMapping, String sourceVersion, Boolean cleanRepository, String workspaceName, String shelveset, String& actualSourceVersion, CancellationToken cancellationToken)
16:17:14.895983 at Microsoft.TeamFoundation.DistributedTask.Plugin.Build.TfvcSourceProvider.<>c__DisplayClass3_0.<PrepareRepositoryAsync>b__0()
16:17:14.895983 --- End of inner exception stack trace ---
There are a lot of similar questions about the 407 proxy authentication error, with suggestions of config files to change, but none specific to the problem of the vNext build agent. Is there a config file somewhere that I can edit to fix this problem?
The config file you need to change is VsoWorker.exe.config, which can be found in the following kind of location C:\BuildAgent\TFS_Build\agent\agent\Worker.
Within the <configuration> block add the following code:
<system.net>
<defaultProxy useDefaultCredentials="true">
</defaultProxy>
</system.net>
I'm using VSTS behind a corporate proxy but have already set my git proxy up globally. If I've done this (so can pull from the collection from the command line) then using the latest vso agent it just works:
https://github.com/Microsoft/vsts-agent

Resources