当前位置:编程学习 > C#/ASP.NET >>

如何使用Membership进行AD用户登陆验证

我是照着MSDN做的,网址:http://msdn.microsoft.com/zh-cn/library/ms998347.aspx使用Membership.ValidateUser()方法,返回的false,使用断点也进入不到Membership类调试,下面是我的代码

一共有三个页面WebForm,一个Login.aspx(登陆页面),Info.aspx(登陆成功跳转到这个页面),Default.aspx(注销页面)

Login.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="WebApplication1.Login" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


Login.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace WebApplication1
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
          
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //点击登陆按钮
            //这里假设已经通过了数据库的对比,确实存在该用户
            string userId = "Test\\admin";
            string pa = "123456";
            string roles = "Administrator";  //从其他地方取得用户角色数据

            if (Membership.ValidateUser(userId, pa))
            {
                FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, userId, DateTime.Now, DateTime.Now.AddMinutes(1), true, roles); //建立身份验证票对象 
                string HashTicket = FormsAuthentication.Encrypt(Ticket); //加密序列化验证票为字符串 
                HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket); //生成Cookie 
                Context.Response.Cookies.Add(UserCookie); //票据写入Cookie 
                Response.Redirect("Info.aspx");
            }
            else
            {
                Response.Write("无效用户名或密码!");
            }
            //为用户名创建一个身份验证票据,并将其添加到响应的Cookie中 
            //以后用户验证都通过这个cookie来维持
            //SetAuthCookie的第一个参数为已验证的用户的名称,一般就是用户id
            //SetAuthCookie的第二个参数为true时代表创建持久Cookie(跨浏览器会话保存的 Cookie)
            //为false则关闭浏览器后要重新验证身份 
            //FormsAuthentication.RedirectFromLoginPage(userId, false);
        }
    }
}


Info.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Info.aspx.cs" Inherits="WebApplication1.Info" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>


Info.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace WebApplication1
{
    public partial class Info : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(User.Identity.IsAuthenticated +"  "+ User.Identity.Name);
        }
    }
}



Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         <asp:Button Text="注销用户" ID="btnLogout" runat="server" 
             onclick="btnLogout_Click"/>
    </div>
    </form>
</body>
</html>


Default.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLogout_Click(object sender, EventArgs e)
        {
            FormsAuthentication.SignOut();
        }
    }
}



web.config

<?xml version="1.0"?>
<configuration>
  <appSettings/>
<connectionStrings>
<add name="ADConnectionString" connectionString="LDAP://192.168.210.152/CN=Users,DC=Test,DC=com"/>
</connectionStrings>

<system.web>
    <compilation debug="true" targetFramework="4.0"/>

<authentication mode="Forms">
<forms loginUrl="Login.aspx"
   protection="All"
   timeout="30"
   name="AppNameCookie"
   path="/FormsAuth"
   requireSSL="false"
   slidingExpiration="true"
   defaultUrl="Default.aspx"
   cookieless="UseCookies"
   enableCrossAppRedirects="false"/>
</authentication>

<authorization>
<deny users="?" />
<allow users="*" />
</authorization>

<membership defaultProvider="MembershipADProvider">
<providers>
<add
  name="MembershipADProvider"
  type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, 
            Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADConnectionString"
connectionUsername="Test\admin" 
                connectionPassword="123456"/>
</providers>
</membership>


<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
  </system.web>

  <!-- 用户角色授权 -->
  <location path="Info.aspx">
    <system.web>
      <authorization>
        <allow roles="Administrator"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
</configuration>


Global.asax

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context; //获取本次Http请求的HttpContext对象 
            if (context.Request.IsAuthenticated) //验证过的一般用户才能进行角色验证 
            {
                FormsIdentity Id = (FormsIdentity)context.User.Identity; //当前用户标识
                FormsAuthenticationTicket Ticket = Id.Ticket; //取得身份证票 
                string[] Roles = Ticket.UserData.Split(','); //将角色数据转成字符串数组,得到相关的角色信息 
                context.User = new System.Security.Principal.GenericPrincipal(Id, Roles); //重新生成带有角色信息的用户
            }
        }
C# Asp.Net .Net AD Active Directory --------------------编程问答-------------------- 怎么没有人?
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,