且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过NTLM冒充用户

更新时间:2023-12-01 08:47:19

让说你Forms身份验证启用ASP.NET应用程序的登录表单的login.aspx和您的用户存储在数据库中。现在,你想支持,窗体和Windows身份验证。这就是我做的:

Let say you have Forms authentication enabled ASP.NET app with login form login.aspx and your users are stored in DB. Now you'd like to support both, Forms and Windows authentication. That's what I do:

有关窗体身份验证我使用SQL与数据库,让说,用户表。我添加到名为WindowsUserName此表新列中,我将在形式的计算机\\用户保存Windows用户名

For forms auth I use SQL DB with, let say, Users table. I add to this table new column named WindowsUserName in which I'll save Windows user's name in form COMPUTER\User

在login.aspx的形式我添加了一个方法,这将发送会显示登录窗口的响应:

In login.aspx form I add a method, which will send a response that will shows login window:

private void ActivateWindowsLogin()
{
    Response.StatusCode = 401;
    Response.StatusDescription = "Unauthorized";
    Response.End();
}

某处我有一个像℃的联系;?login.aspx的使用=窗口A HREF =>联系< / A>

在login.aspx的Page_Load中我已经加入:

In login.aspx Page_Load I have added:

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是我的方法只是样品。

GetUserIdForWindowsUser and GetApplicationUser are my methods just for sample.