Asp.net forms authentication to avoid duplication

Source: Internet
Author: User

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 ModelCopy 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 MethodCopy 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:

CodeCopy 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 userCopy 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. aspxCopy 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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.