【发布时间】:2021-11-10 00:50:14
【问题描述】:
我正在构建一个应用程序来连接到使用行级安全性的数据库。
我正在使用 EF Core 进行连接,通过研究我发现,只要在服务器上运行应用程序的用户有权模拟用户,它就可以使用 Execute as login = [user login] 执行查询。
我有一个方法,在我的数据库上下文工厂启动新上下文后调用。
public static void ChangeUser(String sUser, DbContext dbContext)
{
System.Data.Common.DbConnection dbCon = dbContext.Database.GetDbConnection();
if (dbCon.State != ConnectionState.Open)
dbCon.Open();
string userInDb;
using (var cmd = dbCon.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("user", sUser));
cmd.CommandText = "SELECT SUSER_NAME()";
userInDb = (string) cmd.ExecuteScalar();
}
if (userInDb.ToLower() == sUser.ToLower()) return;
using (var cmd = dbCon.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("user", sUser));
cmd.CommandText = "EXECUTE AS LOGIN = @user;";
cmd.ExecuteNonQuery();
}
}
这适用于最初的几次调用,但最终我得到错误:ERROR|Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost|Unhandled exception in circuit 'n1Y3qPEm60j0xxOFc6O83IrFu3jHD7EQI0_zPnO_2RQ'. Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot continue the execution because the session is in the kill state. A severe error occurred on the current command. The results, if any, should be discarded. 并查看 SQL 服务器上的日志,我通过日志获得更多信息:The connection has been dropped because the principal that opened it subsequently assumed a new security context, and then tried to reset the connection under its impersonated security context. This scenario is not supported. See "Impersonation Overview" in Books Online.
在不会导致连接“终止状态”的情况下,如何正确模拟使用 EF 核心的用户?
我认为这是因为 Execute as 被调用了两次,所以我尝试在尝试冒充用户之前添加检查。
【问题讨论】:
-
您不能在 SQL 服务器上禁止用户模拟吗?
-
SQL server 有行级限制。我正在尝试对其进行设置,以便我的中间件用户(运行应用程序池的用户)可以使用中间件(Intranet web api)模拟经过身份验证的用户
标签: c# entity-framework-core impersonation