Create a secure Web site in ASP.NET

xiaoxiao2021-03-06  113

Creating security in ASP.NET web site Author: Unknown Hits: 4641 Joined: 2003-5-30 14:04:27 before using ASP, PHP, when writing website code JSP, site security is always a headache Things, although we wrote the 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 verification, our processing method is to click any page when the user does not verify, and the specific code is as follows: But this will generate a problem, That is if I have some information that can be freely accessed by any user, such as the 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 above two questions, 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 "> <ask: label id =" message "runat =" server "forecolor =" # ff0000 "> </ asp: label> </ td> </ tr> <tr> <td valign =" 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 "width =" 120 "textmode =</p> <p>"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"> <asp: imagebutton id = " Btnlogin "Runat =" server "imageurl =" / images / w2k / login / btnlogin.gif "> </ asp: imagebutton> </ td> </ tr> </ table> </ form> </ body> </ After the HTML> interface is ready, you will start writing a submission button event. First, you need to register the event, the code is as follows: private void initializecomponent () {this.btnlogin.click = new system.web.ui.ImageClicKeventrandler (this.btnlogin_click); ...} After the event is registered, it is natural to write an event handler: private void btnlogin_click (object sender, system.web.ui.immondb sql = new ccommondb (); string redirect = ""; 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!"; The information is written to the session, cookie, and SQL databases while jumps to the Default.aspx page.</p> <p>As follows: CCommonDB.cs namespace secure.Components {public class CCommonDB: CSql {public CCommonDB (): base () {} 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); if (nLoginID = 0!) // Success {// Log the user inSystem.Web.Security.FormsAuthentication.SetAuthCookie (nLoginID.ToString (), bPersist); // Set the session varaibles objSession [ "loginID"] = nLoginID.ToString (); objSession [ "loginType"] = nLoginType.ToString (); // 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.addday; 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 responseobjResponse.Cookies.Add ( WrapperCookie; objresponse.cookies.add (lgntypecookie); return "/candidate/default.aspx"; }case 1: // admin login {return" /admin/default.aspx";} code 2: // reporting login { Return "/reports/default.aspx"; }default:/return string.empty;}}} else}}}} else}}}} else}}}} else}}}} else}}}} else}}}}} else}}}}}}}} /// <summary> /// Verifier the login and password That Were given // / </ summary> /// <param name = "email"> The login </ param> /// <</p> <p>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 (); // Set our parametersSqlParameter paramLogin = new SqlParameter ( "@ username", SqlDbType.VarChar , 100); paramLogin.Value = email; SqlParameter paramPassword = new SqlParameter ( "@ password", SqlDbType.VarChar, 20); paramPassword.Value = password; Command.CommandType = CommandType.StoredProcedure; Command.CommandText = "glbl_Login"; Command.Parameters.Add (paramlogin); Command.Parameters; Adapter.TableMappings.Add ("Table", "Login"); adapter.selectcommand = Command; Adapter.Fill (DS); if (DS. Tables.count! = 0) {DATAROW ROW = DS.TABLES [0] .ROWS [0]; // Get the login id and the login type1loginid = Convert.Toint32 (Row ["Login_ID"]. TOSTRING ()); Nlogintype = convert.Toint32 (Row ["Login_Type"]. TOSTRING ());} else {nlog inID = 0; nLoginType = 0;}}} abstract public class CSql {private SqlConnection sqlConnection; // Connection stringprivate SqlCommand sqlCommand; // Commandprivate SqlDataAdapter sqlDataAdapter; // Data Adapter private DataSet sqlDataSet; // Data Set public CSql () { sqlConnection = new SqlConnection (ConfigurationSettings.AppSettings [ "ConnectionString"]); sqlCommand = new sqlCommand (); sqlDataAdapter = new SqlDataAdapter (); sqlDataSet = new DataSet (); sqlCommand.Connection = sqlConnection;} /// <summary></p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-126540.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="126540" 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.044</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 = 'V_2BITRY_2B7QglTQ9MOMRzLRMISd_2BpKw12RvTbe1EsIRSLP6gadm7cb92ZGj5Y6Ot22NTC4AGRONRkDC_2BO6JsaMzQ_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>