假設您已經啓用了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