【发布时间】:2012-02-22 09:40:39
【问题描述】:
早上好,
我有一个 asp.net 项目,其中一个表单(身份验证设置为无)针对第三方服务器验证用户凭据,然后在验证后将用户重定向到受保护的内容。
我想做的是从这些凭据创建一个 WindowsIdentity,以便我可以访问我服务器上的其他 WindowsAuthentication 页面以及网络上的其他页面。
这可能吗?
【问题讨论】:
早上好,
我有一个 asp.net 项目,其中一个表单(身份验证设置为无)针对第三方服务器验证用户凭据,然后在验证后将用户重定向到受保护的内容。
我想做的是从这些凭据创建一个 WindowsIdentity,以便我可以访问我服务器上的其他 WindowsAuthentication 页面以及网络上的其他页面。
这可能吗?
【问题讨论】:
您需要使用 LogonUser API 函数来模拟您的调用(并且您还需要帐户登录名和密码,因此您可以使用此函数)。
看看这篇文章,它解释了如何做到这一点:http://msdn.microsoft.com/en-us/library/ff647404.aspx。
这是本文中的代码 sn-p,只是为了了解这种方法。
try
{
// Create a token for DomainName\Bob
// Note: Credentials should be encrypted in configuration file
bool result = LogonUser("Bob", "DomainName",
"P@ssw0rd",
LogonSessionType.Network,
LogonProvider.Default,
out token);
if (result)
{
WindowsIdentity id = new WindowsIdentity(token);
// Begin impersonation
impersonatedUser = id.Impersonate();
// Log the new identity
Response.Write(String.Format(
"</p>Identity after impersonation: {0}<br>",
WindowsIdentity.GetCurrent().Name));
// Resource access here uses the impersonated identity
}
else
{
Response.Write("</p>LogonUser failed: " +
Marshal.GetLastWin32Error().ToString());
}
}
catch
{
// Prevent any exceptions that occur while the thread is
// impersonating from propagating
}
finally
{
// Stop impersonation and revert to the process identity
if (impersonatedUser != null)
impersonatedUser.Undo();
// Free the token
if (token != IntPtr.Zero)
CloseHandle(token);
}
【讨论】: