我采用FormsAuthentication来验证登录,然而还需要在该验证生成的cookie保存其他的值,并且在登录后改动该cookie。这里登录验证的数据是从数据库表来判断,而不是在web.config写死用户列表(其实我认为这里没多大意义)。我有以下几个疑问:1、FormsAuthentication.Authenticate方法实现认证,是不是只能读取config中的用户名和密码;而如何设置从自己设计的用户表中呢??2、也就是生成验证票来认证,先把相关代码贴出来if(CUser.IsExist("a","a"))   //判断数据库中是否有该用户
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, 
txtUser.Text, 
DateTime.Now, 
DateTime.Now.AddMinutes(30),
true,    // 这里我也有疑问,就是设置为true是不是以后用户就不用在该机器登录了,直接启动ie即可访问,那上面时间还代表什么??
txtUser.Text, 
FormsAuthentication.FormsCookiePath); string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
hash); 
         //这里对该cookie还要附加另外的值,比如A
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; Response.Cookies.Add(cookie);
string returnUrl = Request.QueryString["ReturnUrl"]; if (returnUrl == null) returnUrl = "./";
Response.Redirect(returnUrl);
}这样是不是就生成了验证票呢?有没有懂机制的解释一下,深表感谢。从个人感觉FormsAuthentication.Authenticate方法才好像完成认证。3、还有一个就是比较简单的,FormsAuthentication.RedirectFromLoginPage(txtUser.Text,false);似乎这一句已经完成了认证,这就有点莫名其妙了。4、到登录后,如何取得该cookie并且读写呢?举例就用cookie的A谢先

解决方案 »

  1.   

    自己顶一下,顺便说一下,后来我测的是,第二种情况并没有完成认证!只是生成了验证票。如何在第二种情况下完成登录呢??而我要将
    string returnUrl = Request.QueryString["ReturnUrl"];if (returnUrl == null) returnUrl = "./";
    Response.Redirect(returnUrl);替换成FormsAuthentication.RedirectFromLoginPage(txtUser.Text,false);这样似乎不妥吧,具体原因我也说不上来
      

  2.   

    用上面的方式,就是原来生成的验证cookie,值就不存在。真奇怪
      

  3.   

    http://www.codeproject.com/aspnet/formsroleauth.asp
      

  4.   

    <%@ Page Language="C#" %>
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Data.SqlClient" %>
    <html>
    <head>
    <title>Login</title>
    </head>
    <script runat="server">
    // If you're using code-behind, make sure you change "private" to
    // "protected" since the .aspx page inherits from the .aspx.cs
    // file's class
    private void btnLogin_Click(Object sender, EventArgs e)
    {
    // Initialize FormsAuthentication, for what it's worth
    FormsAuthentication.Initialize(); // Create our connection and command objects
    SqlConnection conn =
     new SqlConnection("Data Source=localhost;Initial Catalog=web;");
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "SELECT roles FROM web WHERE username=@username " +
     "AND password=@password"; // Fill our parameters
    cmd.Parameters.Add("@username", SqlDbType.NVarChar, 64).Value =
    Username.Value;
    cmd.Parameters.Add("@password", SqlDbType.NVarChar, 128).Value =
     FormsAuthentication.HashPasswordForStoringInConfigFile(
    Password.Value, "md5"); // Or "sha1" // Execute the command
    conn.Open();
    SqlDataReader reader = cmd.ExecuteReader();
    if (reader.Read())
    {
     // Create a new ticket used for authentication
     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
    1, // Ticket version
    Username.Value, // Username associated with ticket
    DateTime.Now, // Date/time issued
    DateTime.Now.AddMinutes(30), // Date/time to expire
    true, // "true" for a persistent user cookie
    reader.GetString(0), // User-data, in this case the roles
    FormsAuthentication.FormsCookiePath);// Path cookie valid for  // Encrypt the cookie using the machine key for secure transport
     string hash = FormsAuthentication.Encrypt(ticket);
     HttpCookie cookie = new HttpCookie(
    FormsAuthentication.FormsCookieName, // Name of auth cookie
    hash); // Hashed ticket  // Set the cookie's expiration time to the tickets expiration time
     if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;  // Add the cookie to the list for outgoing response
     Response.Cookies.Add(cookie);  // Redirect to requested URL, or homepage if no previous page
     // requested
     string returnUrl = Request.QueryString["ReturnUrl"];
     if (returnUrl == null) returnUrl = "/";  // Don't call FormsAuthentication.RedirectFromLoginPage since it
     // could
     // replace the authentication ticket (cookie) we just added
     Response.Redirect(returnUrl);
    }
    else
    {
     // Never tell the user if just the username is password is incorrect.
     // That just gives them a place to start, once they've found one or
     // the other is correct!
     ErrorLabel = "Username / password incorrect. Please try again.";
     ErrorLabel.Visible = true;
    } reader.Close();
    conn.Close();
    }
    </script>
    <body>
    <p>Username: <input id="Username" runat="server"
    type="text"/><br />
    Password: <input id="Password" runat="server" type="password"/><br
    />
    <asp:Button id="btnLogin" runat="server" OnClick="btnLogin_Click"
     Text="Login"/>
    <asp:Label id="ErrorLabel" runat="Server" ForeColor="Red"
     Visible="false"/></p>
    </body>
      

  5.   

    uop怎么没人具体回答啊?
    自己顶一下
      

  6.   

    我自己是这么干滴   供参考
    private void ButtonLogin_Click(object sender, System.EventArgs e)
    {
    if(this.IsValid)
    {
                    PublicDB.ClassPublicDB.AuthenticateUserEntry authUser = new PublicDB.ClassPublicDB.AuthenticateUserEntry();
    authUser.AuthenticateUser(Server.HtmlDecode(this.TextUserCode.Value.Trim())
    , Server.HtmlDecode(this.TextUserPassword.Value.Trim()), Session.Timeout); if(authUser.IsAuthenticated)
    {
    PublicDB.ClassPublicDB.UserLog login = new SalesPromotion.PublicDB.ClassPublicDB.UserLog();
    int result = login.CheckUserOnline(authUser.UserCode);
    if(result != -1)
    {
    if((Session["LoginID"] != null) && ((int)Session["LoginID"] != -1))
    {
    login.UserLogout(result);
    FormsAuthentication.SignOut();
    Session.RemoveAll();
    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, authUser.EncTicket));
    Session["UserCode"] = authUser.UserCode;
    Session["UserName"] = authUser.UserName;
    Session["IsAuthenticated"] = true;
    login.UserLogin(authUser.UserCode,"IP:"+Request.UserHostAddress);
    Session["LoginID"] = login.LoginID;
    Response.Redirect("Default.aspx");
    }
    else
    {
    Response.Write("<script>alert('有相同的用户已经登录了系统,如果是非法退出请等待5分钟后再试!');</script>");
    }
    }
    if(result == -1)
    {
    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, authUser.EncTicket));
    Session["UserCode"] = authUser.UserCode;
    Session["UserName"] = authUser.UserName;
    Session["IsAuthenticated"] = true;
    login.UserLogin(authUser.UserCode,"IP:"+Request.UserHostAddress);
    Session["LoginID"] = login.LoginID;
    Response.Redirect("Default.aspx");
    }
    }
    else
    {
    Response.Write("<script>alert('用户或密码错误!');</script>");
    }
    }
    }
      

  7.   

    1.是的,如果你要存其它信息,可以自己生成票据,参考http://dev.csdn.net/develop/article/18/18958.shtm,你可以把信息写到UserData里。
    2。是的,生成了票据。
    3。是的,完成了验证并返回最初请求的页面。
    4。如果只取用户名,可以:HttpContext.User.Identity.Name
    如果要取票据的所有信息,可以:
     FormsAuthenticationTicket Ticket = HttpContext。User.Identity .Ticket ;
      

  8.   

    config---------------><authentication mode="Forms" > 
    <forms loginUrl="login.aspx"></forms>
    </authentication>
    <authorization>
    <deny users="?"/>
    </authorization>.CS----------------->string UserName=this.TextBox1.Text.Trim();
    FormsAuthentication.RedirectFromLoginPage(UserName,false);
    Response.Redirect("default.aspx?User="+this.TextBox1.Text.Trim());得到用户名----------》 User.Identity.Name注销----------------》FormsAuthentication.SignOut();
      

  9.   

    如何在验证票上附加自己的数据呢,我怎么添加cookie后,不是登录不了,就是cookie不成功
      

  10.   

    see
    http://dev.csdn.net/develop/article/18/18958.shtm
      

  11.   

    看了上面的文章,非常不错。可我在使用FormsAuthenticationTicket的UserData时,这个属性竟然在验证票生成后不能修改。说是只读的。是不是这样啊??那该怎么办呢
      

  12.   

    可以重新生成票据,然后再写回去.如果是经常变化的数据,不建议写到票据里,写到其它cookie里比较好.
      

  13.   

    用窗体验证还不如在页面的pageload里边if(session!=null)
      

  14.   

    TO:回复人: syq8107(帅土) ( ) 信誉:100  2005-01-25 16:47:00  得分: 0  
     
       用窗体验证还不如在页面的pageload里边if(session!=null)
      
     
    呵呵。。这个好像是ASP思想。
      

  15.   

    按照微软提供的几个例子,窗体验证写在登录页面,用户的附加信息,如用户信息、权限等在Global.asax的Application_AuthenticateRequest节中判断并写入,这是例子中的一段内容:
    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
     string userInformation = String.Empty;
     if (Request.IsAuthenticated == true) 
     {
    // Create the roles cookie if it doesn't exist yet for this session.
    if ((Request.Cookies[UserRoles] == null) || (Request.Cookies[UserRoles].Value == "")) 
    {
    // Retrieve the user's role and ID information and add it to
    // the cookie
    TTUser user = new TTUser(User.Identity.Name);
    if (!user.Load())
    {
    // The user was not found in the Time Tracker database so add them using
    // the default role.  Specifying a UserID of 0 will result in the user being 
    // inserted into the database.
    TTUser newUser = new TTUser(0, Context.User.Identity.Name,
    String.Empty, ConfigurationSettings.AppSettings[CfgKeyDefaultRole]);
    newUser.Save();
    user = newUser;
    }
    // Create a string to persist the role and user id
    userInformation = user.UserID + ";" + user.Role + ";" + user.Name;
    // Create a cookie authentication ticket.
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,                              // version
    User.Identity.Name,     // user name
    DateTime.Now,                   // issue time
    DateTime.Now.AddHours(1),       // expires every hour
    false,                          // don't persist cookie
    userInformation                    
    );
    // Encrypt the ticket
    String cookieStr = FormsAuthentication.Encrypt(ticket);
    // Send the cookie to the client
    Response.Cookies[UserRoles].Value = cookieStr;
    Response.Cookies[UserRoles].Path = "/";
    Response.Cookies[UserRoles].Expires = DateTime.Now.AddMinutes(1);
    // Add our own custom principal to the request containing the user's identity, the user id, and
    // the user's role 
    Context.User = new CustomPrincipal(User.Identity, user.UserID, user.Role, user.Name);
    }
    else 
    {
    // Get roles from roles cookie
    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[UserRoles].Value);
    userInformation = ticket.UserData;
    // Add our own custom principal to the request containing the user's identity, the user id, and
    // the user's role from the auth ticket
    string [] info = userInformation.Split( new char[] {';'} );
    Context.User = new CustomPrincipal(
    User.Identity, 
    Convert.ToInt32(info[0].ToString()), 
    info[1].ToString(),
    info[2].ToString());
    }
    }
    }
      

  16.   

    取出:
    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[UserRoles].Value);
    string userInformation = ticket.UserData;