Problem: It is said that using forms authentication cannot get more information about the current Login User except the user name. After some small experiments, the userdata that comes with forms can be used as a place for us. The following is a record of my operation steps.
Step 1: Key Points of web. config Configuration:
Web. config Configuration
Copy codeThe Code is as follows:
<! --
You can use the <authentication> section to configure ASP. NET
Identifies
Security Authentication mode.
-->
<Authentication mode = "Forms">
<Forms loginUrl = "login. aspx" defaultUrl = "index. aspx"
Name = ". ztinfozero" path = "/Manager"
SlidingExpiration = "true" timeout = "10"> </forms>
</Authentication>
<Authorization>
<Deny users = "? "/>
</Authorization>
Step 2: Construct SiteUser Model
Copy codeThe Code is as follows:
TopicUser Model
[Serializable]
Public class TopicUser
{
Public TopicUser (){}
Model # region model
Private System. Int32 _ autoID;
/** // <Summary>
///
/// </Summary>
Public System. Int32 autoID
{
Get {return _ autoID ;}
Set {_ autoID = value ;}
}
Private System. String _ UserName;
/** // <Summary>
/// User Name
/// </Summary>
Public System. String UserName
{
Get {return _ UserName ;}
Set {_ UserName = value ;}
}
Private System. String _ UserChName;
/** // <Summary>
/// Real name
/// </Summary>
Public System. String UserChName
{
Get {return _ UserChName ;}
Set {_ UserChName = value ;}
}
Private System. String _ UserPass;
/** // <Summary>
///
/// </Summary>
Public System. String UserPass
{
Get {return _ UserPass ;}
Set {_ UserPass = value ;}
}
Private System. String _ DepartMent;
/** // <Summary>
///
/// </Summary>
Public System. String DepartMent
{
Get {return _ DepartMent ;}
Set {_ DepartMent = value ;}
}
Private System. String _ Duty;
/** // <Summary>
///
/// </Summary>
Public System. String Duty
{
Get {return _ Duty ;}
Set {_ Duty = value ;}
}
Private System. Int32 _ UserPermit;
/** // <Summary>
///
/// </Summary>
Public System. Int32 UserPermit
{
Get {return _ UserPermit ;}
Set {_ UserPermit = value ;}
}
Private System. Int32 _ Status;
/** // <Summary>
///
/// </Summary>
Public System. Int32 Status
{
Get {return _ Status ;}
Set {_ Status = value ;}
}
# Endregion
}
Step 3: create a user logon code:
Database-User Logon Method
Copy codeThe Code is as follows:
Public TopicUser UserLogon (string username, string pass ){
String proc = "dbo. infozero_Proc_userLogOn ";
Database db = DataFactory. userDB;
DbCommand cmd = db. GetStoredProcCommand (proc );
Db. AddInParameter (cmd, "@ username", DbType. String, username );
Db. AddInParameter (cmd, "@ userpass", DbType. String, pass );
Db. AddOutParameter (cmd, "@ result", DbType. Int32, 4 );
DataSet ds = db. ExecuteDataSet (cmd );
TopicUser user = null;
Int result = 0;
If (int. TryParse (db. GetParameterValue (cmd, "@ result"). ToString (), out result ))
User = tableToUser (ds. Tables [0]);
Return user;
}
# Region table to user
Private TopicUser tableToUser (DataTable dt ){
TopicUser model = null;
If (dt. Rows. Count> 0 ){
Model = new TopicUser ();
DataRow dr = dt. Rows [0];
Int aid = 0;
Int. TryParse (dr ["autoID"]. ToString (), out aid );
Model. autoID = aid;
Model. UserName = dr ["UserName"]. ToString ();
Model. UserChName = dr ["UserChName"]. ToString ();
Model. UserPass = dr ["UserPass"]. ToString ();
Model. DepartMent = dr ["DepartMent"]. ToString ();
Model. Duty = dr ["Duty"]. ToString ();
If (dr ["UserPermit"]. ToString ()! = "")
{
Model. UserPermit = int. Parse (dr ["UserPermit"]. ToString ());
}
If (dr ["Status"]. ToString ()! = "")
{
Model. Status = int. Parse (dr ["Status"]. ToString ());
}
}
Return model;
}
# Endregion
Step 4: Create a logon page:
Code
Copy codeThe Code is as follows:
Protected void btnOK_Click (object sender, EventArgs e)
{
String username = tbname. Text. Trim ();
String pass = tbpass. Text. Trim ();
If (! String. IsNullOrEmpty (username )){
If (! String. IsNullOrEmpty (pass )){
DataService. User B = new DataService. User ();
DataService. TopicUser user = B. UserLogon (username, pass );
If (user! = Null ){
// Roles, userid | userchname
String userdata = string. Format ("{0}, {1} | {2 }",
User. UserPermit, user. autoID, user. UserChName );
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (
, Username, DateTime. Now, DateTime. Now. AddHours (2 ),
True, userdata );
String encticket = FormsAuthentication. Encrypt (ticket );
HttpCookie cookie = new HttpCookie (
FormsAuthentication. FormsCookieName, encticket );
Response. Cookies. Add (cookie );
Response. Redirect ("Index. aspx ");
}
}
}
}
Step 5: add the Application_AuthenticateRequest event to global. asax to set the information of the current logon User:
Copy codeThe Code is as follows:
Protected void Application_AuthenticateRequest (object sender, EventArgs e)
{
HttpCookie cookie = Context. Request. Cookies [FormsAuthentication. FormsCookieName];
If (cookie! = Null ){
FormsAuthenticationTicket ticket = FormsAuthentication. Decrypt (cookie. Value );
If (ticket! = Null ){
String [] roles = ticket. UserData. Split (',');
FormsIdentity id = new FormsIdentity (ticket );
System. Security. Principal. GenericPrincipal principal = new GenericPrincipal (id, roles );
Context. User = principal;
}
}
}
Step 6: obtain information about the current logon user
Copy codeThe Code is as follows:
Public static TopicUser CurrentUser {
Get {
DataService. TopicUser user = new DataService. TopicUser ();
FormsIdentity identity = HttpContext. Current. User. Identity as FormsIdentity;
FormsAuthenticationTicket ticket = identity. Ticket;
String userdata = ticket. UserData; // get the custom UserData string
If (! String. IsNullOrEmpty (userdata )){
If (userdata. IndexOf (',')> 0 & userdata. IndexOf ('|')> 0)
{
// Roles, userid | userchname
String uinfo = userdata. Split (',') [1];
String [] u = uinfo. Split ('| ');
Int uid = 0;
Int. TryParse (u [0], out uid );
User. autoID = uid;
User. UserChName = u [1];
User. UserName = HttpContext. Current. User. Identity. Name;
}
}
Return user;
}
}
The User ID is UserBase. CurrentUser. autoID. The real name is UserBase. CurrentUser. UserChName;
Determine whether the role of the Current User is administrator: HttpContext. Current. User. IsInRole ("1"); // 1 is administrator
How to exit the current Logon:
LogOut. aspx
Copy codeThe Code is as follows:
Protected void Page_Load (object sender, EventArgs e)
{
System. Web. Security. FormsAuthentication. SignOut ();
Response. Write ("<script> window. top. location = 'login. aspx '; </script> ");
Response. End ();
}
So far, authentication is complete. We don't have to worry about piling up the user's login judgment code.