在 SQL Server 公共语言运行时(CLR)集成中,使用 Windows 身份验证很复杂,但比使用 SQL Server 身份验证更安全。 使用 Windows 身份验证时,请谨记下列注意事项:
默认情况下,连出至 Windows 的 SQL Server 进程会获得 SQL Server Windows 服务帐户的安全上下文。 但是,可以将 CLR 函数映射到代理标识,以便其出站连接与 Windows 服务帐户的安全上下文不同。
在某些情况下,你可能希望使用 SqlContext.WindowsIdentity 属性而不是作为服务帐户运行来模拟调用方。
WindowsIdentity 实例表示调用代码的客户端的标识,并且仅在客户端使用 Windows 身份验证时可用。 获取 WindowsIdentity 实例后,可以调用 Impersonate 以更改线程的安全令牌,然后代表客户端打开 ADO.NET 连接。
调用 SQLContext.WindowsIdentity.Impersonate 后,无法访问本地数据,并且无法访问系统数据。 若要再次访问数据,必须调用 WindowsImpersonationContext.Undo。
以下示例演示如何使用 SqlContext.WindowsIdentity 属性模拟调用方。
Visual C#
WindowsIdentity clientId = null;
WindowsImpersonationContext impersonatedUser = null;
clientId = SqlContext.WindowsIdentity;
// This outer try block is used to protect from
// exception filter attacks which would prevent
// the inner finally block from executing and
// resetting the impersonation.
try
{
try
{
impersonatedUser = clientId.Impersonate();
if (impersonatedUser != null)
return GetFileDetails(directoryPath);
else return null;
}
finally
{
if (impersonatedUser != null)
impersonatedUser.Undo();
}
}
catch
{
throw;
}
注释
有关模拟中的行为更改的信息,请参阅 SQL Server 2014 中数据库引擎功能的中断性变更。
此外,如果获取了 Microsoft Windows 标识实例,则默认情况下无法将该实例传播到另一台计算机;默认情况下,Windows 安全基础结构会限制该基础结构。 但是,有一种称为“委派”的机制,可用于跨多个受信任的计算机传播 Windows 标识。 可以在 TechNet 文章“Kerberos 协议转换和约束委派”中了解有关委派的详细信息。