EF Core为什么使用Domain\MachineName而不是提供的连接字符串User Id?

huangapple go评论74阅读模式
英文:

Why is EF Core using the Domain\MachineName instead of the provided connection string User Id?

问题

使用EF Core时,SQL查询发送了错误的SQL身份验证用户名。

我们得到了Login failed for user '{DOMAIN}{MACHINE NAME}',而不是{DOMAIN}{User Id}

但是当查看我们的日志时,我们看到了这个

Microsoft.Data.SqlClient.SqlException (0x80131904): Login failed for user 'Domain\MachineName$'.

我们正在使用IIS托管此应用程序。我不认为这应该有影响,但我们启用了匿名身份验证,禁用了Windows身份验证。

请注意,由于上下文的不足,某些内容可能无法完全理解或翻译。

英文:

Question

When using EF Core the SQL queries are sending the wrong username for SQL authentication.

We get Login failed for user '{DOMAIN}\{MACHINE NAME}' instead of {DOMAIN}\{User Id}

EF Core为什么使用Domain\MachineName而不是提供的连接字符串User Id?

"Database": "Server=data.example.com;Database=example_data;Trusted_Connection=true;encrypt=no; user id=example; pwd=examplepassword;MultipleActiveResultSets=true"

But when looking at our logs we see this

EF Core为什么使用Domain\MachineName而不是提供的连接字符串User Id?

Microsoft.Data.SqlClient.SqlException (0x80131904): Login failed for user 'Domain\MachineName$'.
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   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.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
   at Microsoft.Data.SqlClient.SqlConnection.Open()
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.<>c.<MoveNext>b__21_0(DbContext _, Enumerator enumerator)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
ClientConnectionId:2e167322-21d0-47ab-bc9b-8d900fec060e
Error Number:18456,State:1,Class:14

We are using IIS to host this application. I don't think this should matter but we have Anonymous Authentication enabled, Windows Authentication is disabled.

Extra Code Bits

Program.cs

using LoadingBlazorWebAssemblyApp.Server.Data;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();

builder.Services.ConfigureDataContexts(builder.Configuration);

var app = builder.Build();

if (app.Environment.IsDevelopment() || app.Environment.IsEnvironment("Test"))
{
    app.UseWebAssemblyDebugging();
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseBlazorFrameworkFiles();
app.UseStaticFiles();

app.UseRouting();


app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");

app.Run();

DB Context Registration

        services.AddDbContext<DataContext>(options =>
            options.UseSqlServer(configuration.GetConnectionString("Database"), s => s.CommandTimeout(180))
            .ConfigureWarnings(warning => warning.Ignore(CoreEventId.StartedTracking))
            .LogTo(message => Debug.WriteLine(message))
            .EnableSensitiveDataLogging());

Provider and version information

EF Core version: 7.0.3

Database provider: Microsoft.EntityFrameworkCore.SqlServer 7.0.3

Target framework: .NET 7.0

Operating system: Windows Server

答案1

得分: 2

我的错误是在我的appsettings.json连接字符串中使用以下选项。

Trusted_Connection=true;

感谢quaabaam和marc_s向我展示了问题并解释了原因。在阅读他们的回复后,我进行了更多的研究,并发现了以下内容

EF Core为什么使用Domain\MachineName而不是提供的连接字符串User Id?

你可以在这个微软页面上找到这些信息。

https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.connectionstring?redirectedfrom=MSDN&view=dotnet-plat-ext-7.0#System_Data_SqlClient_SqlConnection_ConnectionString

英文:

My mistake was using the following option in my appsettings.json connection string.

Trusted_Connection=true;

Thank you to quaabaam and marc_s for showing me the issue and explaining the reason. Upon reading their responses I did some more research and found the following

EF Core为什么使用Domain\MachineName而不是提供的连接字符串User Id?

You can find this information on this page from Microsoft.

https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.connectionstring?redirectedfrom=MSDN&view=dotnet-plat-ext-7.0#System_Data_SqlClient_SqlConnection_ConnectionString

huangapple
  • 本文由 发表于 2023年4月7日 03:57:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953308.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定