假设您已经启用了Forms身份验证ASP.NET应用程序,其登录表单login.aspx并且您的用户存储在数据库中。现在您想要支持Forms和Windows身份验证。这就是我所做的:
对于窗体auth我使用SQL DB,让说,用户表。我添加到名为WindowsUserName此表的新列中,我将在形式的计算机\用户
在login.aspx的形式我添加了一个方法,这将发送会显示登录窗口的响应保存Windows用户名:
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
}
GetUserIdForWindowsU ser和GetApplicationUser是我的方法,仅用于示例。
事情是,两个身份验证方案管理网站的两个不同部分,我不能混用它们。我打算将它们分成两个不同的应用程序。完成后 - 我可以使用Forms AuthCookie,但仍然使用域帐户进行验证。 – 2009-08-18 19:55:27