Sql server 2008 如何获取HttpModule以向SqlServer进行身份验证
我需要向HttpModule添加一个数据库调用。我使用了与IIS托管的WCF服务相同的连接字符串,但是HttpModule无法进行身份验证。(我们使用Windows身份验证,是的,WCF服务进行身份验证) 我返回的错误消息是用户域\machinename$'登录失败Sql server 2008 如何获取HttpModule以向SqlServer进行身份验证,sql-server-2008,iis-7.5,httpmodule,Sql Server 2008,Iis 7.5,Httpmodule,我需要向HttpModule添加一个数据库调用。我使用了与IIS托管的WCF服务相同的连接字符串,但是HttpModule无法进行身份验证。(我们使用Windows身份验证,是的,WCF服务进行身份验证) 我返回的错误消息是用户域\machinename$'登录失败 我需要做什么才能让HttpModule在Sql Server 2008上进行身份验证?为了防止其他人遇到与我相同的问题,下面是一个可行的答案。大部分代码都是从MSDN站点获取的…它可以工作。但实际上,您要做的是模拟您需要的用户 将这
我需要做什么才能让HttpModule在Sql Server 2008上进行身份验证?为了防止其他人遇到与我相同的问题,下面是一个可行的答案。大部分代码都是从MSDN站点获取的…它可以工作。但实际上,您要做的是模拟您需要的用户 将这些添加到您的使用中
using System.Web.Security;
using System.Runtime.InteropServices;
using System.Security.Principal;
编写以下方法:
private bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}
在需要的地方实施
if (impersonateValidUser("username", "domain", "password"))
{
// code that needs to access Db
// make sure you undo when no longer needed
impersonationContext.Undo();
}
以防其他人遇到与我相同的问题,这里有一个可行的答案。大部分代码都是从MSDN站点获取的…它可以工作。但实际上,您要做的是模拟您需要的用户 将这些添加到您的使用中
using System.Web.Security;
using System.Runtime.InteropServices;
using System.Security.Principal;
编写以下方法:
private bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}
在需要的地方实施
if (impersonateValidUser("username", "domain", "password"))
{
// code that needs to access Db
// make sure you undo when no longer needed
impersonationContext.Undo();
}
您的SQL用户名和密码是在连接字符串中指定的,还是依赖Windows身份验证?您的SQL用户名和密码是在连接字符串中指定的,还是依赖Windows身份验证?