Create a secure Web site in ASP.NET

zhaozj2021-02-16  50

In the past, the site security is always a headache, although we have written user login, registration, verification page, but the effect is always not ideal. Sometimes we have to use a large number of session variables to store relevant information, we will be in place. In the .NET environment, this problem is very easy. The key is to fully understand the Web.config file. First, describe the web.config file.

tag to each error to be processed. -> Authorized this section to set the application Authorization strategy. The application resource can be allowed or rejected to access the user or role. Wildcard: "*" means anyone, "?" Indicates anonymous (unauthorized) user. -> - (comma-separated user list] "Roles =" [comma-separated role List] "/> ->

-> Ok, I believe that after reading the above introduction, I must know very well for web.config files. Let it be. Below we will cut the subject. In order to prevent the user from accessing the site without verifying, our processing method is when the user does not pass the validation, click any page to be jumped directly to the login.aspx page, the specific code is as follows:

But this will generate a problem, that is, if some of my site has some information, any user can access, such as site profile, use instructions, etc. If you don't let users feel troublesome, huh, huh, not anxious, naturally have a corresponding solution in ASP.NET. The following code can implement anonymous user access Test.aspx page:

Solved the two questions above, I believe that everyone must have it. The Login.aspx page is started below. Use C # and SQL Server2000 to create a WebForm page, join the appropriate controls. The specific code is as follows:

<% @ Page language = "c #" codebehind = "login.aspx.cs" autoeventwireup = "false" inherits = "secure.login"%> secure site </ title> <meta content =" Microsoft Visual Studio 7.0 "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 MS_POSITIONING = "GridLayout"> <form id = "login" method = "post" runat = "server"> <table cellspacing = "0" cellpadding = "0" border = "0"> <tr> <td valign = "top" align = "left"> < ASP: Label ID = "Message" runat = "server" forcolor = "# ff0000"> </ asp: label> <td> </ tr> <tr> <td value = "top" align = "left"> <b> e-mail: </ b> <td> </ tr> <tr> <td value = "top" align = "left"> <ask: textbox id = "username" runat = "server" width = "120"> </ Asp: textbox> </ td> </ tr> <tr> <td value = "top" align = "left"> <b> password: </ b></p> <p></ td> </ tr> <tr> <td valign = "TOP" align = "left"> <ask: textbox id = "password" runat = "server" width = "120" textmode = "password"> < / asp: textbox> </ td> </ tr> <tr> <td value = "TOP" align = "left"> <ask: checkbox id = "savelogin" runat = "server" text = "<b> save My login </ b> "> </ asp: checkbox> </ td> </ tr> <tr> <td value =" top "align =" right "> <ask: imagebutton id =" btnlogin "runat =" Server "imageurl =" / images / w2k / login / btnlogin.gif "> </ asp: imagebutton> </ td> </ tr> </ table> </ form> </ body> </ html> interface is good After that, you will start writing a submission button event. First, you need to register the event, the code is as follows:</p> <p>Private vidin.click = new system.web.ui.imageClickeventHandler (this.btnlogin_click);......................................</p> <p>Private void btnlogin_click (object sender, system.web.ui.imageClickevenTargs e) {ccommondb sql = new ccommondb (); string redirect = ""</p> <p>if (! (redirect = sql.AuthenticateUser (this.Session, this.Response, username.Text, password.Text, saveLogin.Checked)) = string.Empty) {// Redirect the user Response.Redirect (redirect);} Else {message.text = "login failed!";} The reader must ask if the CCOMMONDB is from the Dongdong, which is the class I wrote, if it is successful The information is written to the session, cookie, and sql database while jumps to the Default.asp page. Specifically, CCOMMONDB.CS</p> <p>Namespace secure.components {public class ccommondb: csql {public ccommondb (): base () {}</p> <p>public string AuthenticateUser (System.Web.SessionState.HttpSessionState objSession, // Session Variable System.Web.HttpResponse objResponse, // Response Variable string email, // Login string password, // Password bool bPersist // Persist login) {int nLoginID = 0; int nlogintype = 0;</p> <p>// log the user in login (email, password, ref nloginid, ref nlogintype);</p> <p>IF (nloginid! = 0) // success {// log the user in system.web.security.formie (nloginid.tostring (), bpersist);</p> <p>// set the session variables objsession ["loginid"] = nloginid.tostring (); objsession ["logintype"] = nlogintype.toString ();</p> <p>// Set cookie information incase they made it persistant System.Web.HttpCookie wrapperCookie = new System.Web.HttpCookie ( "wrapper");. WrapperCookie.Value = objSession [ "wrapper"] ToString (); wrapperCookie.Expires = DateTime. Now.AddDays (30); System.Web.HttpCookie lgnTypeCookie = new System.Web.HttpCookie ( "loginType");. lgnTypeCookie.Value = objSession [ "loginType"] ToString (); lgnTypeCookie.Expires = DateTime.Now.AddDays (30); // add the cookie to the response objresponse.cookies.add (wrappercookie); objresponse.cookies.add (lgntypecookie);</p> <p>Return "/candidate/default.aspx";} case 1: // admin login {return "/admin/default.aspx";} case 2: // reporting login {return "/reports/default.aspx";} default : {Return String.empty;}}} else {return</p> <p>/// <summary> /// Verifier the login and password That WERE GIVEN /// </ / summary> /// <param name = "email"> the login </ param> /// <param name = "Password > The password </ param> /// <param name = "nloginid"> Returns the login ID </ param> /// <param name = "nlogintype"> Returns the login type </ param> public void login String email, string password, ref int nloginid, ref int nlogintype) {resetsql ();</p> <p>DataSet DS = New DataSet ();</p> <p>// Set our parameters SqlParameter paramLogin = new SqlParameter ( "@ username", SqlDbType.VarChar, 100); paramLogin.Value = email; SqlParameter paramPassword = new SqlParameter ( "@ password", SqlDbType.VarChar, 20); paramPassword.Value = Password;</p> <p>Command.commandtype = commandType.StoredProcedure; command.commandtext = "glbl_login"; command.parameters.add (paramlogin); Command.Parameters.Add (parampassword);</p> <p>Adapter.tableMappings.add ("Table", "Login"); adapter.selectcommand = Command; Adapter.Fill (DS);</p> <p>IF (ds.tables.count! = 0) {DATAROW ROW = DS.TABLES [0] .rows [0];</p> <p>// get the login id and the login type nloginid = convert.toint32 (row ["login_id"]. TOSTRING ()); nlogintype = convert.toint32 (row ["login_type"]. Tostring ());} else {nloginid = 0; nlogintype = 0;}}}</p> <p>abstract public class CSql {private SqlConnection sqlConnection; // Connection string private SqlCommand sqlCommand; // Command private SqlDataAdapter sqlDataAdapter; // Data Adapter private DataSet sqlDataSet; // Data Set</p> <p>public CSql () {sqlConnection = new SqlConnection (ConfigurationSettings.AppSettings [ "ConnectionString"]); sqlCommand = new SqlCommand (); sqlDataAdapter = new SqlDataAdapter (); sqlDataSet = new DataSet ();</p> <p>Sqlcommand.connection = sqlConnection;</p> <p>/// <summary> /// Access to out u {{{return sqlCommand;}}</p> <p>/// <summary> /// Access to our data adapter /// </ summary> protected sqldataadapter adapter {get {return sqldataadapter;}} /// <summary> /// Makes Sure Thathes Clear and Ready for a new query /// </ summary> protected void ResetSql () {if (sqlCommand = null!) {sqlCommand = new sqlCommand (); sqlCommand.Connection = sqlConnection;} if (! sqlDataAdapter = null) sqlDataAdapter = new SqlDataAdapter ( );</p> <p>IF (SqlDataSet! = null) sqldataset = new dataset ();</p> <p>/// <summary> /// Runs out /// </ summary> /// <returns> The data set </ returns> protected dataset runquery () {sqldataadapter.selectCommand = Command;</p> <p>SqlConnection.open (); sqlConnection.close ();</p> <p>SqlDataAdapter.Fill (SqlDataSet);</p> <p>Return SqlDataSet;}}}</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-24221.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="24221" 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.043</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 = 'zOs67r0bkDFIIhz41vspOaWSCcZGqPbwQUlSC9fKVga0_2BREjsiAtLRvpBbbvYPkpE7r785vv_2BD4cIXn8O_2BPuyA_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>