Create a secure Web site in ASP.NET

xiaoxiao2021-03-06  39

When using ASP, PHP, JSP to write website code, 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. ->

->

Ok, I believe that after reading the introduction above, I must know very well for web.config files. 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:

solves the above two questions, I believe everyone I must have an end in my heart. 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> </ td> </ Tr> <Tr> <TD Valign = "TOP" align = "left"> <ask: textbox id = "password" runat = "server" W IDTH = "120" textmode = "</p> <p>Password "> </ asp: textbox> </ td> </ tr> <TD value =" TOP "align =" left "> <ask: checkbox id =" savelogin "runat =" server "text =" <B> Save My Login </ B>> </ asp: checkbox> </ td> </ tr> <tr> <td valign = "top" align = "right"> <ask: imagebutton id = "btnlogin "Runat =" server "imageurl =" / images / w2k / login / btnlogin.gif "> </ asp: imagebutton> </ td> </ tr> </ table> </ form> </ body> </ html > After the interface is done, you will start writing a submission button event. First, you need to register the event, the code is as follows:</p> <p>Private void initializecomponent () {this.btnlogin.click = new system.web.ui.imageClickeventHandler (this.btnlogin_click); ...} The event is naturally written in the event handler:</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 userResponse.Redirect (redirect);} else {Message.Text = "Login Failed!"; Write relevant information to session, cookie, and sql databases while jump to the Default.aspx page. details as follows:</p> <p>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 VariableSystem.Web.HttpResponse objResponse, // Response Variablestring email, // Loginstring password, // Passwordbool bPersist // Persist login) {int nLoginID = 0; int NLogintype = 0; // log the user inlogin (email, password, ref nloginid, ref nlogintype);</p> <p>IF (nloginid! = 0) // success {// log the user insystem.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 persistantSystem.Web.HttpCookie wrapperCookie = new System.Web.HttpCookie ( "wrapper");. WrapperCookie.Value = objSession [ "wrapper"] ToString (); wrapperCookie.Expires = DateTime.Now .Adddays (30);</p> <p>System.Web.HttpCookie lgnTypeCookie = new System.Web.HttpCookie ( "loginType");. LgnTypeCookie.Value = objSession [ "loginType"] ToString (); lgnTypeCookie.Expires = DateTime.Now.AddDays (30);</p> <p>// Add the cookie to the responseobjresponse.cookies.add (wrappercookie); objresponse.cookies.add (lgntypecookie);</p> <p>Return "/candidate/default.aspx";} code 1: // admin login {return" /admin/default.aspx";} code 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 (); dataset ds = new dataset ();</p> <p>// set out our parametersqlparameter paramlogin = new SQLParameter ("@ username", sqldbtype.varchar, 100); paramlogin.value = email;</p> <p>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 type1loginid = 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 stringprivate SqlCommand sqlCommand; // Commandprivate 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 (); 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;}}</p> <p>/// <Summary> /// Makes Sure That Everything Clear And Ready for a New Query //// </ summary> protected void recsql () {if (sqlcommand! = null) {sqlcommand = new sqlcommand (); SQLCommand .Connection = sqlconnection;}}}} f (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-51940.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="51940" 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 = 'HhZgkPfUMKsvcYKZUfp1UsuYeTCnIm89f74l2krQlL22XdkRuZxZvequmlyzt5ZZMgHQ852N4ZQxenFazoeMzQ_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>