使用userData存储Role

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    
if (HttpContext.Current.User != null)
     {
       
if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
          
if (HttpContext.Current.User.Identity is FormsIdentity)
           {
             
// Get Forms Identity From Current User
             FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
             
// Get Forms Ticket From Identity object
                FormsAuthenticationTicket ticket = id.Ticket;
            
// Retrieve stored user-data (our roles from db)
               string userData = ticket.UserData;
               
string[] roles = userData.Split(',');
               
// Create a new Generic Principal Instance and assign to Current User
               HttpContext.Current.User = new GenericPrincipal(id, roles);
             }
        }
    }
}



相关的登录代码:
private void Button1_Click(object sender, System.EventArgs e)
{
    
// Initialize FormsAuthentication (reads the configuration and gets 
    
// the cookie values and encryption keys for the given application)
    FormsAuthentication.Initialize();

    
// Create connection and command objects
    SqlConnection conn =
    
new SqlConnection("Data Source=PETER;Database=Northwind;User ID=sa;password=;");
    conn.Open();
    SqlCommand cmd 
= conn.CreateCommand();
    cmd.CommandText 
= "SELECT roles FROM Employees WHERE username=@username " +
    
"AND password=@password"// this should really be a stored procedure, right?

    
// Fill our parameters
    cmd.Parameters.Add("@username", SqlDbType.NVarChar, 64).Value = TextBox1.Text;
    cmd.Parameters.Add(
"@password", SqlDbType.NVarChar, 64).Value = TextBox2.Text;
    FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text, 
"sha1");
    
// you can use the above method for encrypting passwords to be stored in the database
    
// Execute the command
    SqlDataReader reader = cmd.ExecuteReader();
    
if (reader.Read())
    {
        
// Create a new ticket used for authentication
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        
1// Ticket version
        TextBox1.Text, // Username to be associated with this ticket
        DateTime.Now, // Date/time issued
        DateTime.Now.AddMinutes(30), // Date/time to expire
        true// "true" for a persistent user cookie (could be a checkbox on form)
        reader.GetString(0), // User-data (the roles from this user record in our database)
        FormsAuthentication.FormsCookiePath); // Path cookie is valid for

        
// Hash the cookie for transport over the wire
        string hash = FormsAuthentication.Encrypt(ticket);
        HttpCookie cookie 
= new HttpCookie(
        FormsAuthentication.FormsCookieName, 
// Name of auth cookie (it's the name specified in web.config)
         hash); // Hashed ticket

        
// Add the cookie to the list for outbound 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 = "LoggedIn.aspx";

        
// Don't call the FormsAuthentication.RedirectFromLoginPage since it could
        
// replace the authentication ticket we just added
        Response.Redirect(returnUrl);
    }
    
else
    {
        
// Username and or password not found in our database
        ErrorLabel.Text = "Username / password incorrect. Please login again.";
        ErrorLabel.Visible 
= true;
    }
}
posted @ 2008-08-12 14:40  王其荣的博客  阅读(268)  评论(0编辑  收藏  举报