假设您使用登录表单 login.aspx 启用了表单身份验证的 ASP.NET 应用程序,并且您的用户存储在 DB 中。现在您希望同时支持表单和 Windows 身份验证。我就是做这个的:
对于表单身份验证,我将 SQL DB 与用户表一起使用。我在此表中添加了名为 WindowsUserName 的新列,其中我将以 COMPUTER\User 形式保存 Windows 用户名
在 login.aspx 表单中,我添加了一个方法,该方法将发送一个显示登录窗口的响应:
private void ActivateWindowsLogin()
{
Response.StatusCode = 401;
Response.StatusDescription = "Unauthorized";
Response.End();
}
在某个地方我有一个链接<a href="login.aspx?use=windows">Admin</a>
在 login.aspx Page_Load 我添加了:
if (Request.QueryString["use"] == "windows")
{
var windowsuser = Request.ServerVariables["LOGON_USER"];
if (windowsuser.Length == 0)
ActivateWindowsLogin();
else
{
// get userId from DB for Windows user that was authenticated by IIS
// I use userId in .ASPXAUTH cookie
var userId = GetUserIdForWindowsUser(windowsuser);
if (userId > 0) //user found
{
// here we get User object to check roles or other stuff
var user = GetApplicationUser(userId);
// perform additional checks here and call ActivateWindowsLogin()
// to show login again or redirect to access denied page.
// If everythig is OK, set cookie and redirect
FormsAuthentication.SetAuthCookie(userId.ToString(), false);
Response.Redirect(FormsAuthentication.GetRedirectUrl(userId.ToString(), false), true);
}
else //user not found
ActivateWindowsLogin();
}
}
else
{
//your Forms auth routine
}
GetUserIdForWindowsUser 和 GetApplicationUser 是我的示例方法。