ログインフォームlogin.aspxを使用してフォーム認証を有効にしたASP.NETアプリがあり、ユーザーがDBに保存されているとします。ここで、フォーム認証と Windows 認証の両方をサポートしたいと考えています。それが私がすることです:
フォーム認証の場合、SQL DB と、たとえば、Users テーブルを使用します。このテーブルに、WindowsUserName という名前の新しい列を追加します。この列には、Windows ユーザーの名前を COMPUTER\User の形式で保存します。
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 はサンプル用のメソッドです。