Use the HTTPContext's user attribute to implement user verification [reproduced]

xiaoxiao2021-03-06  14

The HTTPContext 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. /// // / Implementation IPRINCIPAL interface public class myprincipal: system.security.principal.iliPrincipal {private system.security.principal.iidentity Identity; private arraylist rolelist;

Public myprincipal (string userid, string password) {// // Todo: Add constructor logic // identity = new myident; if (Identity.isauthenticated) {// Get it if verified The user's role, which can be modified to read the specified user's role and add it to the Role. This example adds an admin role RoleList = new arraylist (); rolelist.add ("admin ");} Else {// do nothing}} public arraylist rolelist;}} #Region iPrIncipal member

Public system.security.principal.iidentity Identity {get {// Todo: Add myprincipal.Identity getter implementation returnidity;} set {identity = value;}}

Public Bool Isinrole (String Role) {// Todo: Add myprincipal.isinrole Implement Return RoleList.Contains (role) ;;}

#ndregion}}}

Myidentity.cs

Using system;

Summary description of Namespace httpContextusereg {///

/// myidentity. /// /// IIdentity implement the interface public class MyIdentity: System.Security.Principal.IIdentity {private string userID; private string password; public MyIdentity (string currentUserID, string currentPassword) {// // TODO: in Add constructor logic // userid = currentuserid; Password = currentpassword;}

Private bool canpass () {/ / The friends here can change to verify the username and password from the database according to their own needs, // Here I can specify the string IF you specified directly (userid == "YAN0lovesha" && password == " "} else {returnaf;}}}

Public string password {get {return password;} set {password = value;}}

#Region IIDENTITY member

Public Bool isauthenticated {get {// Todo: Add myidentity.isauthenticated getter Implement Return canpass ();}}

PUBLIC STRING NAME {Get {// Todo: Add myidentity.name getter Implement Return UserID;}} // This property We can use it according to your needs, in this case, there is no use of 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;

A summary description of Namespace httpContextusereg {///

/// mypage. /// /// Inherit from Page class public class mypage: system.Web.ui.page {public mypage () {// // Todo: Add constructor logic //}

Protected Override Void OnInit (Eventargs E) {Base.onit (E); this.Load = New EventHandler (mypage_load);}

// Extract user information from the cache when the page is loaded, the user information private void mypage_load (ipxt.user.Identity.isAuthentic) {if (Context.cache ["UserMessage"]! = NULL ) {Hashtable userMessage = (Hashtable) Context.Cache [ "UserMessage"];. MyPrincipal principal = new MyPrincipal (userMessage [ "UserID"] ToString (), userMessage [ "UserPassword"] ToString ());. Context.User = The following 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> <meta content =" Microsoft Visual Studio .NET 7.1 "Name =" Generator "> <meta content =" c # " name = "CODE_LANGUAGE"> <meta content = "JavaScript" name = "vs_defaultClientScript"> <meta content = "http://schemas.microsoft.com/intellisense/ie5" name = "vs_targetSchema"> </ HEAD> <body > <Form id = "form1" method = "post" runat = "server"> <p> <font face = "Song"> User Name: <asp: textbox id = "tbxuserid" runat = "server"> </ ASP: TextBox> <br> Password: <asp: textbox id = "tbxpassword" runat = "server" textmode = "password"> </ asp: textbox> <font> <p> <font face = "Song"> <ask = "btnlogin" runat = "server" text = "login"> </ asp: button> <ask: label id = "LBLLoginm Essage "Runat =" Server "> </ asp: label> </ font> <font fold =" Song "> <ask: panel id =" panel1 "runat =" server "visible =" False> <p></p> <p><ask: button id = "btnadmin" runat = "server" text = "role 1"> </ asp: button> <ask: button id = "btnuser" runat = "server" text = "role 2"> </ ASP: Button> </ p> <p> <asp: label id = "lblroleMessage" runat = "server"> </ asp: label> <p> </ asp: panel> <p> </ p> < / Font> </ form> </ body> </ html> Webform1.aspx.cs</p> <p>using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Caching; using System.Web.SessionState; using System.Web.UI; using System.Web.ui.WebControls; use system.web.ui.htmlcontrols;</p> <p>Namespace httpcontextusereg {/// <summary> /// WebForm1 summary description. /// </ summary> /// here will have been changed to inherit from the Page class inherits from our own MyPage class public class WebForm1: HttpContextUserEG.MyPage {protected System.Web.UI.WebControls.TextBox tbxUserID; protected System.Web .UI.WebControls.TextBox tbxPassword; protected System.Web.UI.WebControls.Panel Panel1; protected System.Web.UI.WebControls.Button btnAdmin; protected System.Web.UI.WebControls.Button btnUser; protected System.Web.UI .WebControls.Label lblRoleMessage; protected System.Web.UI.WebControls.Label lblLoginMessage; protected System.Web.UI.WebControls.Button btnLogin; private void Page_Load (object sender, System.EventArgs e) {// Put user here Code to initialize page}</p> <p>#Region Web Form Designer Generated Code Override Protected Void OnNit (Eventargs E) {// // Codegen: This call is required for the ASP.NET Web Form Designer. // InitializeComponent (); base.onit (e);} /// <summary> /// Designer Supports the required method - Do not use the code editor to modify the // / this method. /// </ summary> private void InitializeComponent () {this.btnLogin.Click = new System.EventHandler (this.btnLogin_Click); this.btnAdmin.Click = new System.EventHandler (this.btnAdmin_Click); this.btnUser .Click = new system.eventhandler (this.btnuser_click; this.load = new system.eventhandler (this.page_load);} #ENDREGION</p> <p>private void btnLogin_Click (object sender, System.EventArgs e) {MyPrincipal principal = new MyPrincipal (tbxUserID.Text, tbxPassword.Text); if (! principal.Identity.IsAuthenticated) {lblLoginMessage.Text = "user name or password is incorrect" Panel1.visible = false;} else {// If the user is verified, save the user information in the cache, after using // In practice, friends can try to save user information using user verification tickets. This is also .NET built-in user processing mechanism context.user = principal; hashtable usermessage = new hashtable (); userMessage.add ("userid", tbxuserid.text); userMessage.Add ("UserPassword", tbxpassword.text); Context.cache.insert ("UserMessage", UserMessage; lblloginMessage.text = tbxuserid.text " Login "; panel1.visible = true;}}</p> <p>Private void btnadmin_click (object sender, system.eventargs e) {// Verify that the user's role contains admin if ("admin") {lblroleMessage.text = "User" (MyPrincipal) Context .User) .Identity.name "belongs to admin group";} else {lblroleMessage.text = "User" Context.user.Identity.name "Not Admin Group";}} private void btnuser_click (Object Sender, System .Eventargs e) {// Verify that the user's Role contains the user if ("User")) {lblroleMessage.Text = "User" Context.user.Identity.name "belongs to User Group" } Else {lblroleMessage.text = "User" Context.User.Identity.name "Does not belong to User group"; }}}}</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. 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></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-67552.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="67552" 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.077</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 = 'VgZyUZmRUe50M_2B03eUxo_2BAV_2F_2BvoAdcg1qpAXCg4Q_2Bdqt_2BfSKnKwRr_2FWGwQpLHtKpympOUC2p3suTxPXzJI_2BFAg_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>