dotnet / aspire

An opinionated, cloud ready stack for building observable, production ready, distributed applications in .NET
https://learn.microsoft.com/dotnet/aspire
MIT License
3.37k stars 350 forks source link

SQL Server service principal connection string issue #4253

Open mercedesyenzzz opened 1 month ago

mercedesyenzzz commented 1 month ago

Hi,

I have noticed that there is an issue since Aspire 8.0.0-preview.7.24251.11.

With 8.0.0-preview.6.24214.1 I could just run this without any issues:

builder.AddSqlServerDbContext<AppDbContext>("test-db");

together with a .NET user-secret in this format:

"ConnectionStrings:test-db" "Server=servernamehere; Authentication=Active Directory Service Principal; Encrypt=True; Database=databasenamehere; User Id=UserID; Password=Password;"

Since preview 7 I am getting the following error when I am using the AppDbContextsomewhere in my app. When I do not use Service Principal Authentication I am not facing any issues.

This is the full error that I am getting:

2024-05-22T10:12:42.8472724 fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
      An error occurred using the connection to database 'databasenamehere' on server 'servernamehere'.
2024-05-22T10:12:42.8566988 fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'CommonLookupClient.AppDbContext'.
      Microsoft.Data.SqlClient.SqlException (0x80131904): ClientSecretCredential authentication failed: AADSTS900023: Specified tenant identifier 'authorize' is neither a valid DNS name, nor a valid external domain. Trace ID: IDHERE Correlation ID: IDHERE Timestamp: 2024-05-22 08:12:42Z
       ---> Azure.Identity.AuthenticationFailedException: ClientSecretCredential authentication failed: AADSTS900023: Specified tenant identifier 'authorize' is neither a valid DNS name, nor a valid external domain. Trace ID: IDHERE Correlation ID: IDHERE Timestamp: 2024-05-22 08:12:42Z
       ---> MSAL.NetCore.4.60.3.0.MsalServiceException:
        ErrorCode: invalid_request
      Microsoft.Identity.Client.MsalServiceException: AADSTS900023: Specified tenant identifier 'authorize' is neither a valid DNS name, nor a valid external domain. Trace ID: IDHERE Correlation ID: IDHERE Timestamp: 2024-05-22 08:12:42Z
         at Microsoft.Identity.Client.OAuth2.OAuth2Client.ThrowServerException(HttpResponse response, RequestContext requestContext)
         at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext)
         at Microsoft.Identity.Client.OAuth2.OAuth2Client.ExecuteRequestAsync[T](Uri endPoint, HttpMethod method, RequestContext requestContext, Boolean expectErrorsOn200OK, Boolean addCommonHeaders, Func`2 onBeforePostRequestData)
         at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint, ILoggerAdapter logger)
         at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint, ILoggerAdapter logger)
         at Microsoft.Identity.Client.OAuth2.TokenClient.SendTokenRequestAsync(IDictionary`2 additionalBodyParameters, String scopeOverride, String tokenEndpointOverride, CancellationToken cancellationToken)
         at Microsoft.Identity.Client.Internal.Requests.RequestBase.SendTokenRequestAsync(IDictionary`2 additionalBodyParameters, CancellationToken cancellationToken)
         at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.GetAccessTokenAsync(CancellationToken cancellationToken, ILoggerAdapter logger)
         at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.ExecuteAsync(CancellationToken cancellationToken)
         at Microsoft.Identity.Client.Internal.Requests.RequestBase.<>c__DisplayClass11_1.<<RunAsync>b__1>d.MoveNext()
      --- End of stack trace from previous location ---
         at Microsoft.Identity.Client.Utils.StopwatchService.MeasureCodeBlockAsync(Func`1 codeBlock)
         at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
         at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenForClientParameters clientParameters, CancellationToken cancellationToken)
         at Azure.Identity.AbstractAcquireTokenParameterBuilderExtensions.ExecuteAsync[T](AbstractAcquireTokenParameterBuilder`1 builder, Boolean async, CancellationToken cancellationToken)
         at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientCoreAsync(String[] scopes, String tenantId, String claims, Boolean enableCae, Boolean async, CancellationToken cancellationToken)
         at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientAsync(String[] scopes, String tenantId, String claims, Boolean enableCae, Boolean async, CancellationToken cancellationToken)
         at Azure.Identity.ClientSecretCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
        StatusCode: 400 
        ResponseBody: {"error":"invalid_request","error_description":"AADSTS900023: Specified tenant identifier 'authorize' is neither a valid DNS name, nor a valid external domain. Trace ID: IDHERE Correlation ID: IDHERE Timestamp: 2024-05-22 08:12:42Z","error_codes":[900023],"timestamp":"2024-05-22 08:12:42Z","trace_id":"IDHERE","correlation_id":"IDHERE","error_uri":"[https://login.microsoftonline.com/error?code=900023"](https://login.microsoftonline.com/error?code=900023%22);} 
        Headers: Cache-Control: no-store, no-cache
      Pragma: no-cache
      Strict-Transport-Security: max-age=31536000; includeSubDomains
      X-Content-Type-Options: nosniff
      P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
      client-request-id: IDHERE
      x-ms-request-id: IDHERE
      x-ms-ests-server: 2.1.18105.6 - WEULR1 ProdSlices
      x-ms-clitelem: 1,900023,0,,
      x-ms-srs: 1.P
      X-XSS-Protection: 0
      Set-Cookie: fpc=FPC; expires=Fri, 21-Jun-2024 08:12:42 GMT; path=/; secure; HttpOnly; SameSite=None, x-ms-gateway-slice=estsfd; path=/; secure; samesite=none; httponly, stsservicecookie=estsfd; path=/; secure; samesite=none; httponly
      Date: Wed, 22 May 2024 08:12:41 GMT

         --- End of inner exception stack trace ---
         at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)
         at Azure.Identity.ClientSecretCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
         at Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.AcquireTokenAsync(SqlAuthenticationParameters parameters)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.<>c__DisplayClass147_1.<<GetFedAuthToken>b__3>d.MoveNext()
      --- End of stack trace from previous location ---
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo)
         at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
         at Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
         at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
      --- End of stack trace from previous location ---
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.<>c__DisplayClass30_0`2.<<ExecuteAsync>b__0>d.MoveNext()
      --- End of stack trace from previous location ---
         at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementationAsync[TState,TResult](Func`4 operation, Func`4 verifySucceeded, TState state, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementationAsync[TState,TResult](Func`4 operation, Func`4 verifySucceeded, TState state, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
      ClientConnectionId:IDHERE
      Microsoft.Data.SqlClient.SqlException (0x80131904): ClientSecretCredential authentication failed: AADSTS900023: Specified tenant identifier 'authorize' is neither a valid DNS name, nor a valid external domain. Trace ID: IDHERE Correlation ID: IDHERE Timestamp: 2024-05-22 08:12:42Z
       ---> Azure.Identity.AuthenticationFailedException: ClientSecretCredential authentication failed: AADSTS900023: Specified tenant identifier 'authorize' is neither a valid DNS name, nor a valid external domain. Trace ID: IDHERE Correlation ID: IDHERE Timestamp: 2024-05-22 08:12:42Z
       ---> MSAL.NetCore.4.60.3.0.MsalServiceException:
        ErrorCode: invalid_request
      Microsoft.Identity.Client.MsalServiceException: AADSTS900023: Specified tenant identifier 'authorize' is neither a valid DNS name, nor a valid external domain. Trace ID: IDHERE Correlation ID: IDHERE Timestamp: 2024-05-22 08:12:42Z
         at Microsoft.Identity.Client.OAuth2.OAuth2Client.ThrowServerException(HttpResponse response, RequestContext requestContext)
         at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext)
         at Microsoft.Identity.Client.OAuth2.OAuth2Client.ExecuteRequestAsync[T](Uri endPoint, HttpMethod method, RequestContext requestContext, Boolean expectErrorsOn200OK, Boolean addCommonHeaders, Func`2 onBeforePostRequestData)
         at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint, ILoggerAdapter logger)
         at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint, ILoggerAdapter logger)
         at Microsoft.Identity.Client.OAuth2.TokenClient.SendTokenRequestAsync(IDictionary`2 additionalBodyParameters, String scopeOverride, String tokenEndpointOverride, CancellationToken cancellationToken)
         at Microsoft.Identity.Client.Internal.Requests.RequestBase.SendTokenRequestAsync(IDictionary`2 additionalBodyParameters, CancellationToken cancellationToken)
         at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.GetAccessTokenAsync(CancellationToken cancellationToken, ILoggerAdapter logger)
         at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.ExecuteAsync(CancellationToken cancellationToken)
         at Microsoft.Identity.Client.Internal.Requests.RequestBase.<>c__DisplayClass11_1.<<RunAsync>b__1>d.MoveNext()
      --- End of stack trace from previous location ---
         at Microsoft.Identity.Client.Utils.StopwatchService.MeasureCodeBlockAsync(Func`1 codeBlock)
         at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
         at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenForClientParameters clientParameters, CancellationToken cancellationToken)
         at Azure.Identity.AbstractAcquireTokenParameterBuilderExtensions.ExecuteAsync[T](AbstractAcquireTokenParameterBuilder`1 builder, Boolean async, CancellationToken cancellationToken)
         at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientCoreAsync(String[] scopes, String tenantId, String claims, Boolean enableCae, Boolean async, CancellationToken cancellationToken)
         at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientAsync(String[] scopes, String tenantId, String claims, Boolean enableCae, Boolean async, CancellationToken cancellationToken)
         at Azure.Identity.ClientSecretCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
        StatusCode: 400 
        ResponseBody: {"error":"invalid_request","error_description":"AADSTS900023: Specified tenant identifier 'authorize' is neither a valid DNS name, nor a valid external domain. Trace ID: IDHERE Correlation ID: IDHERE Timestamp: 2024-05-22 08:12:42Z","error_codes":[900023],"timestamp":"2024-05-22 08:12:42Z","trace_id":"IDHERE","correlation_id":"IDHERE","error_uri":"[https://login.microsoftonline.com/error?code=900023"](https://login.microsoftonline.com/error?code=900023%22);} 
        Headers: Cache-Control: no-store, no-cache
      Pragma: no-cache
      Strict-Transport-Security: max-age=31536000; includeSubDomains
      X-Content-Type-Options: nosniff
      P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
      client-request-id: IDHERE
      x-ms-request-id: IDHERE
      x-ms-ests-server: 2.1.18105.6 - WEULR1 ProdSlices
      x-ms-clitelem: 1,900023,0,,
      x-ms-srs: 1.P
      X-XSS-Protection: 0
      Set-Cookie: fpc=FPC; expires=Fri, 21-Jun-2024 08:12:42 GMT; path=/; secure; HttpOnly; SameSite=None, x-ms-gateway-slice=estsfd; path=/; secure; samesite=none; httponly, stsservicecookie=estsfd; path=/; secure; samesite=none; httponly
      Date: Wed, 22 May 2024 08:12:41 GMT

         --- End of inner exception stack trace ---
         at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)
         at Azure.Identity.ClientSecretCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
         at Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.AcquireTokenAsync(SqlAuthenticationParameters parameters)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.<>c__DisplayClass147_1.<<GetFedAuthToken>b__3>d.MoveNext()
      --- End of stack trace from previous location ---
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo)
         at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
         at Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
         at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
      --- End of stack trace from previous location ---
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.<>c__DisplayClass30_0`2.<<ExecuteAsync>b__0>d.MoveNext()
      --- End of stack trace from previous location ---
         at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementationAsync[TState,TResult](Func`4 operation, Func`4 verifySucceeded, TState state, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementationAsync[TState,TResult](Func`4 operation, Func`4 verifySucceeded, TState state, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
      ClientConnectionId:IDHERE
mitchdenny commented 1 month ago

Could you provide a bit more detail about your setup. What is in your apphost?

mercedesyenzzz commented 1 month ago

I am using .NET SDK 8.0.300 & I am developing on WSL2 (Ubuntu 22.04.4 LTS)

My apphost is very basic. But for testing I trimmed it down to this now:

using Projects;

var builder = DistributedApplication.CreateBuilder(args);

builder.AddProject<MyAPI>("my-api");

builder.Build().Run();

Also with this minimalistic config I am getting the error (Aspire version 8.0.1). In my API project I am using these Aspire Nuget packages:

    <PackageReference Include="Aspire.Azure.Security.KeyVault" Version="8.0.1" />
    <PackageReference Include="Aspire.Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.1" />

I could figure out that this is related to Aspire.Azure.Security.KeyVault. When I have this package in my csproj I am getting the error message from above. This is also the case when I am not registering the service via:

builder.Configuration.AddAzureKeyVaultSecrets("secrets");

in my Program.cs.

mitchdenny commented 1 month ago

I noticed that you are saying that you are using Aspire.Azure.Security.KeyVault and Aspire.Microsoft.EntityFrameworkCore.SqlServer but you don't have any calls to AddAzureKeyVault(...) or AddSqlServer(...) in your AppHost.

Does this mean that you are manually configuring the connection strings for those in your MyAPI project's appsettings/user secrets?

You can let Aspire help you here by just doing this:

var builder = DistributedApplication.CreateBuilder(args);
var db = builder.AddSqlServer("sql").AddDatabase("db");
var kv = builder.AddAzureKeyVault("kv");
builder.AddProject("my-api")
       .WithReference(db)
       .WithReference(kv);

When you run, Aspire will take care of creating the KeyVault resource and also spinning up the SQL server in a container.

mercedesyenzzz commented 1 month ago

Yes I know that but I am using databases that do already exist on different servers. So to connect to them in dev I put in the ConnectionString in the format described above into dotnet user secrets. I played around with the Azure KeyVault component because I am planning to use that in production.

However, the issue that I was facing is still very strange in my opinion. I have different microservices that are connected to different (already existing) databases. I have one microservice that is also connected to an SQL Server DB but uses SQL Authentication. Not facing any issues in this case also when I am using the Aspire.Azure.Security.KeyVault Nuget package in that application.

mitchdenny commented 3 weeks ago

For a pre-existing database you should be using the following:

var db = builder.AddConnectionString("preexisting");

Then for your user secrets you want to add one for ConnectionStrings:preexisting with the connection string to that database. Aspire will pick that up and pass it in as a reference.

mitchdenny commented 1 week ago

@mercedesyenzzz did this solve the issue for you?

leetmike commented 1 week ago

@mitchdenny I wanted to chime in here. I am having a similar issue with the latest SqlClient / Azure.Identity and service principal auth without using .net aspire. The exact same exception… it seems to be sending invalid parameters to the MS OAuth endpoint.

I think this is a bug outside of aspire, I need to do more PoC today and report this because it’s causing issues for a few of our apps that recently updated these as part of a transitive package.

mitchdenny commented 1 week ago

Thanks for the heads up. If you do get a repro can you share it here too? Especially if you raise an issue elsewhere, it'll help us keep track of things.

mercedesyenzzz commented 2 days ago

Do you have any updates or a good workaround for this ?

It is currently a big blocker for us -.-

mercedesyenzzz commented 1 day ago

@leetmike did you already reported that issue?

mercedesyenzzz commented 21 hours ago

Did some more troubleshooting. I don't think that this issue is related to Azure.Identity. When I use:

<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.3.1" /> instead of <PackageReference Include="Aspire.Azure.Security.KeyVault" Version="8.0.2" /> everything works fine.