User Verification of HTTPCONText

xiaoxiao2021-03-06  42

Transfer from: http://blog.9cbs.net/yan0lovesha/archive/2005/01/13/252508.aspxhttpContext class contains all specific HTTP information for individual HTTP requests. This example is mainly how to use the user attribute in the HTTPContext class to implement user authentication!

User authentication is that most ASP.NET web applications are used, which posses a very important status throughout the application. In .NET, there are many user authentication methods, such as well-known Passport authentication, Windows certification , Form certification, etc., it is difficult to meet our needs in practical applications, so that many friends are all written by themselves to implement their own features, which makes us consideration in security and system efficiency. .

In fact, the user verification mechanism built in the ASP.NET is very powerful, and it also has very good scalability, which can generate an attribute called User in the HTTPContext object. This property allows us to access various information. , Including whether the user has verified, the user's type, user name, etc. We can also expand the functionality of this property to achieve our requirements.

Objects assigned to HTTPContext.user must implement an IPRINCIPAL interface, one of the IPrInCIPAL defined attributes is Identity, which must implement the IIDENTITY interface. Because we only need to write classes that implement these two interfaces, we can add any of these classes we need.

First, we create two classes that implement iPrincipal and IIDENTITY, divided by another Myiprincipal and MyIndentity

Myiprincipal.cs

Using system;

Using system.collections;

Namespace httpcontextusereg

{

///

/// myPrincipal's summary description.

///

// / Implement an IPRINCIPAL interface

Public class myprincipal: system.security.principal.iprincipal

{

Private system.security.principal.iziDentity Identity;

Private arraylist rolelist;

Public myprincipal (String Userid, String Password)

{

//

// TODO: Add constructor logic here

//

Identity = New MyIdentity (userID, password);

Ide (Identity.isauthenticated)

{

// If you get the user's Role, you can modify it from the database.

/ / Read the specified user's role and add it to the Role, add an admin role to the user directly in this example

RoleList = new arraylist ();

RoleList.Add ("admin");

}

Else

{

// do nothing

}

}

Public ArrayList RoleList

{

get

{

Return RoleList;

}

}

#Region iPrincipal member

Public system.security.principal.iziDentity Identity

{

get

{

// Todo: Add myprincipal.Identity getter implementation

Return Identity;

}

set

{

Identity = value;}

}

Public Bool Isinrole (String Role)

{

// Todo: Add myprincipal.isinrole implementation

Return RoleList.Contains (Role) ;;

}

#ndregion

}

}

Myidentity.cs

Using system;

Namespace httpcontextusereg

{

///

/// myidentity's summary description.

///

// / Implement the IIDENTITY interface

Public class myidentity: system.security.principal.iidentity

{

Private string userid;

PRIVATE STRING Password;

Public MyIdentity (String CurrentUserid, String CurrentPassword)

{

//

// TODO: Add constructor logic here

//

Userid = CurrentUserId;

Password = currentpassword;

}

Private bool canpass ()

{

/ / The friends here can change the user name and password from the database according to their needs.

/ / Here, I can easily specify the string directly specified.

IF (userid == "yan0lovesha" && password == "ioveshasha")

{

Return True;

}

Else

{

Return False;

}

}

Public String Password

{

get

{

Return Password;

}

set

{

Password = Value;

}

}

#Region IIDENTITY member

Public Bool Isauthenticated

{

get

{

// Todo: Add myidentity.isauthenticate getter implementation

Return canpass ();

}

}

Public String Name

{

get

{

// Todo: Add myidentity.name getter implementation

Return UserId;

}

}

// This property we can use according to your needs, it is not used in this example.

Public String AuthenticationType

{

get

{

// Todo: Add myidentity.AuthenticationType getter implementation

Return NULL;

}

}

#ndregion

}

}

After completing these two classes, we also have to create a self-proven, here we are named mypage, inheriting from page classes.

Mypage.cs

Using system;

Using system.collections;

Namespace httpcontextusereg

{

///

A summary description of /// mypage.

///

/// Inherited from Page class

Public class mypage: system.web.ui.page

{

Public mypage ()

{

//

// TODO: Add constructor logic here

//

}

Protected Override Void OnNit (Eventargs E)

{

Base.onit (E);

This.Load = New EventHandler (mypage_load);

}

// Extract user information from the cache when loading

Private void mypage_load (Object Sender, System.EventArgs E)

{

IF (context.user.Identity.isauthenticated)

{

IF (Context.Cache ["UserMessage"]! = null)

{

Hashtable UserMessage = (Hashtable) Context.cache ["UserMessage"];

MyPrincipal Principal = New MyPrincipal (UserMessage ["Userid"]. TOSTRING (), userMessage ["userpassword"]. TOSTRING ());

CONTEXT.USER = Principal;

}

}

}

}

}

Below is our interface WebForm.aspx and WebForm.aspx.cs

WebForm.aspx

<% @ Page language = "c #" codebehind = "Webform1.aspx.cs" autoeventwireup = "false" inherits = "httpContextusereg.webform1"%>%>

3C

// DTD HTML 4.0 Transitional // En ">

Webform1 </ Title></p> <p><meta content = "Microsoft Visual Studio .NET 7.1" Name = "Generator"></p> <p><meta content = "c #" Name = "code_language"></p> <p><meta content = "javascript" name = "vs_defaultclientscript"></p> <p><meta content = "http://schemas.microsoft.com/intellisense/ie5" Name = "vs_targetschema"></p> <p></ HEAD></p> <p><body></p> <p><form id = "form1" method = "post" runat = "server"></p> <p><P> <font face = "Song"> User Name:</p> <p><asp: textbox id = "tbxuserid" runat = "server"> </ asp: textbox> <br></p> <p>Password:</p> <p><ask: textbox id = "tbxpassword" runat = "server" textmode = "password"> </ ask: textbox> </ font> </ p></p> <p><P> <font face = "Song"></p> <p><ask: button id = "btnlogin" runat = "server" text = "login"> </ asp: button> <ask: label id = "lblloginmessage" runat = "server"> </ asp: label> </ font > </ P></p> <p><P> <font face = "Song"></p> <p><asp: panel id = "panel1" runat = "server" visible = "false"></p> <p><P></p> <p><asp: button id = "btnadmin" runat = "server" text = "role 1"> </ asp: button></p> <p><asp: button id = "btnuser" runat = "server" text = "role 2"> </ asp: button> </ p></p> <p><P></p> <p><asp: label id = "lblroleMessage" runat = "server"> </ asp: label> </ p></p> <p></ asp: panel></p> <p><P> </ p></p> <p></ Font></p> <p></ form></p> <p></ body></p> <p></ Html></p> <p>Webform1.aspx.cs</p> <p>Using system;</p> <p>Using system.collections;</p> <p>Using system.componentmodel;</p> <p>Using system.data;</p> <p>Using system.drawing;</p> <p>Using system.Web;</p> <p>Using system.Web.caching;</p> <p>Using system.Web.SessionState;</p> <p>Using system.Web.ui;</p> <p>Using system.Web.ui.webcontrols;</p> <p>Using system.Web.ui.htmlcontrols;</p> <p>Namespace httpcontextusereg</p> <p>{</p> <p>/// <summary></p> <p>/// WebForm1 summary description.</p> <p>/// </ summary></p> <p>/// will inherit it here from the Page class to inherit yourself MyPage class</p> <p>Public Class Webform1: httpContextUsereg.mypage</p> <p>{</p> <p>Protected system.web.ui.webcontrols.textbox tbxuserid;</p> <p>Protected system.Web.ui.WebControls.TextBox TBXpassword;</p> <p>protected system.web.ui.webcontrols.panel panel1;</p> <p>protected system.web.ui.webcontrols.button btnadmin</p> <p>protected system.web.ui.webcontrols.button btnuser;</p> <p>Protected system.web.ui.webcontrols.label lblroleMessage;</p> <p>Protected system.Web.ui.webcontrols.label lblloginmessage;</p> <p>protected system.web.ui.webcontrols.button btnlogin; private void page_load (Object Sender, System.Eventargs E)</p> <p>{</p> <p>/ / Place the user code here to initialize the page</p> <p>}</p> <p>#Region web form designer generated code</p> <p>Override protected void oninit (Eventargs E)</p> <p>{</p> <p>//</p> <p>// Codegen: This call is necessary for the ASP.NET Web Form Designer.</p> <p>//</p> <p>InitializationComponent ();</p> <p>Base.onit (e);</p> <p>}</p> <p>/// <summary></p> <p>/// Designer supports the required method - do not use the code editor to modify</p> <p>/// This method is content.</p> <p>/// </ summary></p> <p>Private vidinitiRizeComponent ()</p> <p>{</p> <p>This.btnlogin.click = new system.eventhandler (this.btnlogin_click);</p> <p>This.btnadmin.click = new system.eventhandler (this.btnadmin_click);</p> <p>This.btnuser.click = new system.eventhandler (this.btnuser_click);</p> <p>This.Load = New System.EventHandler (this.page_load);</p> <p>}</p> <p>#ndregion</p> <p>Private void btnlogin_click (Object Sender, System.EventArgs E)</p> <p>{</p> <p>MyPrincipal Principal = New MyPrincipal (TBXUserId.Text, TBXPassword.Text);</p> <p>IF (!principal.Identity.isauthenticated)</p> <p>{</p> <p>LBLLoginMessage.Text = "Username or Password is incorrect";</p> <p>Panel1.visible = false;</p> <p>}</p> <p>Else</p> <p>{</p> <p>// If the user passes the verification, the user information is saved in the cache, and it is used after</p> <p>// In practice, friends can try to save user information using user verification tickets, which is also .NET built-in user processing mechanism</p> <p>CONTEXT.USER = Principal;</p> <p>Hashtable UserMessage = new hashtable ();</p> <p>UserMessage.Add ("UserID", TBXUserId.Text);</p> <p>UserMessage.Add ("Userpassword", TBXPassword.text);</p> <p>Context.cache.insert ("UserMessage", UserMessage;</p> <p>LBLLoginMessage.text = tbxUserid.text "Logged in";</p> <p>Panel1.visible = true;</p> <p>}</p> <p>}</p> <p>Private void btnadmin_click (Object Sender, System.Eventargs E)</p> <p>{</p> <p>/ / Verify that the user's role contains admin</p> <p>IF (Context.user.Isinrole ("admin")))</p> <p>{</p> <p>LBLROLEMESSAGE.TEXT = "User" ((MyPrincipal) Context.user) .Identity.name "belongs to the admin group";</p> <p>}</p> <p>Else</p> <p>{</p> <p>LBLROLEMESSAGE.TEXT = "User" Context.user.Identity.name "Does not belong to admin group";</p> <p>}</p> <p>Private void btnuser_click (Object Sender, System.EventArgs E)</p> <p>{</p> <p>/ / Verify that the user's Role contains User</p> <p>IF (Context.user.Isinrole ("User"))</p> <p>{</p> <p>LBLROLEMESSAGE.TEXT = "User" Context.user.Identity.name "belongs to User Group";</p> <p>}</p> <p>Else</p> <p>{</p> <p>LBLROLEMESSAGE.TEXT = "User" Context.User.Identity.name "Does Not Alone User Group";</p> <p>}</p> <p>}</p> <p>}</p> <p>}</p> <p>The code part is over, friends can try to see the effect, in this example, in this example, for the convenience, in practical applications, these will be from the database or from other configuration files, and this The scalability of the method is very high, we can extend the functionality of the MyIPrincipal and Myidentity classes according to your needs. For example, we can add an isinpermission to make the user not only a role, but each role can also have different permissions. In this example, it is also possible to try the user verification ticket by using the cache to save the user's verification.</p> <p>We can see that this user verification mechanism, the more favorable in our program, the more benefits it, and he still has a lot worthy of our discovery!</p> <p>I hope everyone can communicate with me! Thank you!</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-68119.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="68119" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.039</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'LHAQlSXYaSqrMIiXZwZBZcbj7jl0OvLdaQJffRRzTJny0g0wPrluy17AT2VGHcMNOyXXBkGxJoH8STBSG9FxDg_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>