企业内小网站兼用Windows验证登录

在企业内一个小软件(Web site),它原本已经有其自己登录验证,匿名验证登录(form方式)。
用户反馈说,登录这个网站,每次还得输入帐户与密码,太过繁锁。用户每次打开电脑已经登录电脑了,是否可以以当前用户登录电脑的信息直接登录这个小软件。

收到反馈,觉得是有改进。

使用VS打开网站(Shift + Alt + O),然后打开Web.config查看网站验证方式,
<!--
  The <authentication> section enables configuration 
  of the security authentication mode used by 
  ASP.NET to identify an incoming user. 
-->
<authentication mode="Windows" />

 

哇,网站原本就是windows验证的。
为什么它又能以form验证呢?原来在IIS有启用匿名验证登录,打开IIS,
2026-05-16_21-43-19

 

前往数据库,把网站的用户表打开,为其添加一个字段,如,

ALTER TABLE [dbo].[Users]
ADD [WorkstationLogin] NVARCHAR(256) NULL


添加后,在网站后台用户管理介面,把域用户(Domain\Account)更新至[WorkstationLogin]字段内。或者在数据库批量更新也行。
使用域用户信息验证,首先得在网站在登录时,获取到当前登录电脑的用户信息。
原本Login.aspx是匿名登录,想获取域用户User.Identity.Name是有点难度,这个需要在windows authentication环境下才可以。

在网站创建一个页面,如GetDomainUser.aspx,让其在windows认证环境下浏览。

<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <%--无需编写任何html markup--%>
        </div>
    </form>
</body>
</html>

 

GetDomainUser.aspx.cs,
2026-05-17_09-30-03

 

打开web.config,添加,

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    
        <!--
          The <authentication> section enables configuration 
          of the security authentication mode used by 
          ASP.NET to identify an incoming user. 
        -->
        <authentication mode="Windows" />
        
    <location path="GetDomainUser.aspx">
        <system.web>
            <authorization>
                <deny users="?" /> <!--禁用匿名访问-->
            </authorization>
        </system.web>
    </location>
</configuration>

 

这样,在浏览GetDomainUser.aspx时,它只能是在windows认证。

接下来,我们需要去Login.aspx页面,添加使用域用户登录的功能,

<asp:TableRow>
    <asp:TableCell>
        <asp:Table ID="Table2" runat="server" Width="100%">
            <asp:TableRow Height="25px">
                <%--此行是为增加域用户登录--%>
                <asp:TableHeaderCell Width="75px">
                </asp:TableHeaderCell>
                <asp:TableHeaderCell Style="text-align: left;">
                    <asp:CheckBox ID="CheckBoxWorkstationLogin" runat="server" Text="Use Workstation Login" Height="23" Font-Bold="false" ForeColor="Black" AutoPostBack="false" OnClick="toggleUserInput(event);" />
                    <asp:HiddenField ID="HiddenFieldDomainName" runat="server" />
                    
                    <asp:HiddenField ID="HiddenFieldVirtualDirectory" runat="server" />
                </asp:TableHeaderCell>
            </asp:TableRow>
            <asp:TableRow Height="25px">
                <asp:TableCell>&nbsp;&nbsp;&nbsp;号(<span style="text-decoration: underline">U</span>)                                                
                </asp:TableCell>
                <asp:TableCell>
                    <asp:TextBox
                        runat="server" ID="txtAccount" AccessKey="U" Width="150px" Height="23"
                        CssClass="txtInput"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidatorAccount" runat="server" ControlToValidate="txtAccount"
                        Display="none" ErrorMessage="帐号栏位请求值。"></asp:RequiredFieldValidator>
                </asp:TableCell>
            </asp:TableRow>
            <asp:TableRow Height="25px">
                <asp:TableCell>&nbsp;&nbsp;&nbsp;码(<span style="text-decoration: underline">W</span>)                                                
                </asp:TableCell>
                <asp:TableCell>
                    <asp:TextBox
                        runat="server" ID="txtPassword" TextMode="Password" AccessKey="W"
                        Width="150px" Height="23" CssClass="txtInput"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidatorPassword" runat="server" ControlToValidate="txtPassword"
                        Display="none" ErrorMessage="密码栏位请求值。"></asp:RequiredFieldValidator>
                </asp:TableCell>
            </asp:TableRow>
            <asp:TableRow Height="25px">
                <asp:TableCell>
                    <span id="spanLabelValidationCode" runat="server" visible="false">验证码(<span style="text-decoration: underline">V</span>)
                    </span>
                </asp:TableCell>
                <asp:TableCell>
                    <span id="spanValidationCode" runat="server" visible="false">
                        <asp:TextBox
                            ID="txtValidationCode" runat="server" AccessKey="V" Width="75px" Height="23"
                            CssClass="txtInput"></asp:TextBox>
                        <img id="imgValidateCode" src='<%=ResolveUrl("~/Front/ValidateCode.aspx") %>'
                            align="absmiddle" height="25" onclick="javascript:this.src='<%=ResolveUrl("~/Front/ValidateCode.aspx?id=") %>' + Math.random();"
                            alt="看不清楚?点击刷新验证码" style="cursor: hand; vertical-align: top;" />
                    </span>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidatorValidationCode" runat="server" ControlToValidate="txtValidationCode"
                        Display="none" ErrorMessage="验证码栏位请求值。"></asp:RequiredFieldValidator>
                </asp:TableCell>
            </asp:TableRow>
            <asp:TableRow Height="25px">
                <asp:TableCell>

                </asp:TableCell>
                <asp:TableCell>
                    <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="true"
                        ShowSummary="false" EnableClientScript="true" />
                    <asp:ImageButton
                        ID="ImageButton1" runat="server" ImageAlign="AbsMiddle" ImageUrl="Front/Image/login.gif"
                        OnClick="SignIn" />
                    &nbsp;
                    <asp:ImageButton runat="server" ImageAlign="AbsMiddle" ID="ImageButton2" CausesValidation="false"
                        OnClick="Forgot_Click" ImageUrl="Front/Image/forgot.gif"></asp:ImageButton>
                </asp:TableCell>
            </asp:TableRow>
        </asp:Table>
    </asp:TableCell>
</asp:TableRow>

 

2026-05-17_09-39-50

 

红色框框,即是新添加的。
复选框,只有检测到获取了User.Identity.Name时才可选或去选。如果没有检测到User.Identity.Name时,复选框是禁用状态。

在打开Login.aspx登录时,用户会看到的
此时,让用户决定是否域认证登录,选中复选框Use Workstation Login,一些用户还没有被管理员在Users表中配置WorkstationLogin的情况,用户只能输入网站用帐号与密码来登录。

修改“登录”按钮事件,

protected void SignIn(object sender, EventArgs e)
{
    if (this.CheckBoxWorkstationLogin.Checked) 
    {
        try
        {
            string identityName = this.HiddenFieldDomainName.Value;
           
                ValidationData(identityName);
           
        }
        catch (Exception ex)
        {
            objInsusJsUtility.JsAlert(ex.Message);
        }
    }
    else
    {           
        try
        {
            string account = this.txtAccount.Text.Trim();
            string password = this.txtPassword.Text.Trim();
            //较验用户输入的验证码是否正确
            if (this.spanLabelValidationCode.Visible && this.spanValidationCode.Visible)
            {
                ValidationCode(txtValidationCode);
            }

            ValidationData(account, password);
        }
        catch (Exception ex)
        {
           //失败,启用验证码,需要用户输入验证才能登录
        }
    }
}

private void ValidationData(string identityName)
{
    DataTable dt = objUsers.LoginWithDomainUser(identityName);
    ValidationData(dt);
}

private void ValidationData(string accountNumber, string password)
{
    DataTable dt = objUsers.LoginVerifyAndGetInfo(accountNumber, password); 
    ValidationData(dt);
}

private void ValidationData(DataTable dt)
{
    DataRow dataRow = dt.Rows[0];
   //登录成功,获取用户信息

   //存入Session或Cookie
   
   //写入log

   //导向成功页面
}

 

修改至此,似乎没有看到GetDomainUser.aspx的引用。在Login.aspx页,写javascript,引用jQuery类库,并依其ajax来呼叫GetDomainUser.aspx网页。获取到User.Identity.Name存入HiddenField中,这样在上面cs的SignIn事件中取到。
2026-05-17_10-05-05

 

 <script type="text/javascript">
     $(document).ready(function () {
         var jsVirtualDirectory = document.getElementById('<%= HiddenFieldVirtualDirectory.ClientID %>').value;
         $.ajax({
             url: jsVirtualDirectory + 'GetDomainUser.aspx',
             method: 'GET',
             xhrFields: { withCredentials: true },   // 携带跨域凭据(同域时可省略)
             success: function (data) {
                 if (data && data.domainUser) {
                     $('#<%= HiddenFieldDomainName.ClientID %>').val(data.domainUser);                       

                     var $chk = $('#<%= CheckBoxWorkstationLogin.ClientID %>');
                     $chk.prop('disabled', false);
                 }
             },
             error: function (xhr, status, error) {
                 // 401 或其他错误,表示未能获取域用户      
                 var $chk = $('#<%= CheckBoxWorkstationLogin.ClientID %>');
                 $chk.prop('checked', false);
                 $chk.prop('disabled', true);
             },
         });
     });
 </script>
View Code

 

本随笔,关键是配置windows认证,IIS和Web.config中的配置。
另外在GetDomainUser.aspx和Login.aspx页中呼叫与应用。

 

posted @ 2026-05-17 10:19  Insus.NET  阅读(19)  评论(0)    收藏  举报