asp.net forms authentication, avoiding repetitive wheel-making-practical tips

Source: Internet
Author: User
Question: Everyone says that using forms validation does not get more information about the current logged-on user than the user name, and after my little experiment, the UserData can be used as a place for us in forms. The following is a note of my steps in the process of memo.
Step 1:web.config configuration key Place:
Web.config configuration
Copy Code code as follows:

<!--
Through the <authentication> section you can configure ASP.net to
Identify the user who entered the
Secure authentication mode.
-->
<authentication mode= "Forms" >
<forms loginurl= "Login.aspx" defaulturl= "index.aspx"
Name= ". Ztinfozero" path= "/manager"
Slidingexpiration= "true" timeout= "ten" ></forms>
</authentication>
<authorization>
<deny users= "?" />
</authorization>

Step 2: Construction SiteUser Model
Copy Code code 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 Login code:

Database-User Login method
Copy Code code 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 login page:

Code
Copy Code code as follows:

protected void Btnok_click (object sender, EventArgs e)
{
String use Rname = 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 in Global.asax to set the information for the currently logged-on User:
Copy Code code 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: How to get the information of the current logged-on user
Copy Code code 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 a 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 ID of the current logged-on user is UserBase.CurrentUser.autoID; The real name is: UserBase.CurrentUser.UserChName;
Determines whether the current user's role is administrator: HttpContext.Current.User.IsInRole ("1"); 1 for Administrators
Exit the current login method:
Logout.aspx
Copy Code code 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 ();
}

At this point, authentication is complete. We don't have to worry about stacking the user's code to determine whether or not to log in.

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.