基于角色的身份验证3

数据库表

 
CREATE 
DATABASE web

CREATE TABLE users
(
    username 
nvarchar(64CONSTRAINT users_PK PRIMARY KEY,
    password 
nvarchar(128),
    roles 
nvarchar(64)
)

CREATE INDEX credentials ON users
(
    username,
    password
)
内容
 格式
 
username  |password      |roles
"hstewart"|"codeproject" |"Administrator,User"
"joe"     |"schmoe"      |"User"

web.config 的设置  
 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    
  
<system.web>

  
    
<compilation 
         
defaultLanguage="c#"
         debug
="true"
    
/>

   
    
<customErrors 
    
mode="RemoteOnly" 
    
/> 

   
 
<authentication mode="Forms">
            
<forms name="MYWEBAPP.ASPXAUTH"
                loginUrl
="login.aspx"
                protection
="All"
                path
="/"/>
        
</authentication>
        
<authorization>
              
<allow users="*"/>
        
</authorization>

    
<trace
        
enabled="false"
        requestLimit
="10"
        pageOutput
="false"
        traceMode
="SortByTime"
        localOnly
="true"
    
/>

    
    
<sessionState 
            
mode="InProc"
            stateConnectionString
="tcpip=127.0.0.1:42424"
            sqlConnectionString
="data source=127.0.0.1;Trusted_Connection=yes"
            cookieless
="false" 
            timeout
="20" 
    
/>

    
<globalization 
            
requestEncoding="utf-8" 
            responseEncoding
="utf-8" 
   
/>
   
 
</system.web>
<location path="administrators">
        
<system.web>
            
<authorization>
                
<!-- Order and case are important below -->
                
<allow roles="Administrator"/>
                
<deny users="*"/>
            
</authorization>
        
</system.web>
    
</location>
    
<location path="users">
        
<system.web>
            
<authorization>
                
<!-- Order and case are important below -->
                
<allow roles="User"/>
                
<deny users="*"/>
            
</authorization>
        
</system.web>
    
</location>
</configuration>
 

    

Global.asax

    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)
                    
{
                        FormsIdentity id 
=
                            (FormsIdentity)HttpContext.Current.User.Identity;
                        FormsAuthenticationTicket ticket 
= id.Ticket;

                        
// Get the stored user-data, in this case, our roles
                        string userData = ticket.UserData;
                        
string[] roles = userData.Split(',');
                        HttpContext.Current.User 
= new GenericPrincipal(id, roles);
                    }

                }

            }


        }
上边的难证代码和下边是一样的,有兴趣可以看一下。。。。 

 
 System.Web .HttpApplication  app=((HttpApplication)sender);
           System.Web.HttpContext  ctx
=app.Context;
            
if (ctx.Request .IsAuthenticated)
   



     login.aspx 
  
private void Button1_Click(object sender, System.EventArgs e)
        
{
            
// Initialize FormsAuthentication, for what it's worth
            FormsAuthentication.Initialize();

            
// Create our connection and command objects
            SqlConnection conn =
                
new SqlConnection("server=localhost;database=web;User ID=sa;password=");
            SqlCommand cmd 
= conn.CreateCommand();
            cmd.CommandText 
= "SELECT roles FROM users WHERE username=@username " +
                
"AND password=@password";

            
// Fill our parameters
            cmd.Parameters.Add("@username", SqlDbType.NVarChar, 64).Value =
                Username.Text;
            cmd.Parameters.Add(
"@password", SqlDbType.NVarChar, 128).Value =
                Password.Text; 
// 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.Text, // 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.Text = "Username / password incorrect. Please try again.";
                ErrorLabel.Visible 
= true;
            }


            reader.Close();
            conn.Close();
        }


在根目录下建 
administrators  目录
users          目录

 两个目录下分别建调用页面 

 调用页面内容
 

  private void Page_Load(object sender, System.EventArgs e)
  
{
   
// 在此处放置用户代码以初始化页面

   
if (User.IsInRole("Administrator"))
    
this.Response .Write ("Administrator"); 
   
if (User.IsInRole ("User"))
    
this.Response .Write ("User");

  }


   

  
  转自

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

原文地址:https://www.cnblogs.com/gwazy/p/166497.html