To create a secure Web site (configuration) in asp.net

Source: Internet
Author: User
Tags config datetime empty log set cookie tostring wrapper visual studio
asp.net|web| Security | create | site

Previously used asp,php,jsp to write site code, site security is always a headache, although we have written a user login, registration, authentication page, but the effect is always unsatisfactory. Sometimes we have to use a lot of session variables to store relevant information, everywhere fortification. And in. NET environment, this problem is very easy to deal with. The key is to fully understand the Web.config file. First, introduce the Web.config file.

<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>

<system.web>

<!--dynamic Debug compilation
Set compilation debug= "True" to debug symbols (. PDB information)
Insert into the compilation page. Because this will create the execution
A slower large file, you should set the value to true only when debugging, and all other times set to
False For more information, please refer to the
Debug the document for the ASP.net file.
-->
<compilation defaultlanguage= "VB" debug= "true"/>

<!--custom error messages
Set CustomErrors mode= "on" or "RemoteOnly" to enable custom error messages, or set to off to disable custom error messages.
Add <error> tag for each error that you want to handle.
-->
<customerrors mode= "RemoteOnly"/>

<!--authentication
This section sets the authentication policy for the application. The possible pattern is \ "Windows\",
\ "Forms\", \ "passport\" and "none\"
-->
<authentication mode= "Windows"/>


<!--authorization
This section sets the authorization policy for the application. Can allow or deny user or role access
Application resources. Wildcard: "*" means any person, "?" means anonymity
(unauthorized) user.
-->
<authorization>
<allow users= "*"/> <!--allow all users-->

<!--<allow users= "[Comma separated list of users]"
roles= "[comma-separated role list]"/>
<deny users= "[Comma separated list of users]"
roles= "[comma-separated role list]"/>
-->
</authorization>

<!--application-level trace records
Application-level tracking enables trace log output for each page within the application.
Set trace Enabled= "True" to enable application trace logging. If pageoutput= "true", the
The trace information is displayed at the bottom of each page. Otherwise, you can pass from the WEB application
Root browses the "Trace.axd" page to view
Application trace log.
-->
<trace enabled= "false" requestlimit= "ten" pageoutput= "false" tracemode= "SortByTime" localonly= "true"/>


<!--session state settings
By default, ASP.net uses cookies to identify which requests belong to a specific session.
If the cookie is not available, you can track the session by adding the session identifier to the URL.
To disable cookies, set sessionstate cookieless= "true".
-->
<sessionstate
Mode= "InProc"
Stateconnectionstring= "tcpip=127.0.0.1:42424"
sqlconnectionstring= "Data Source=127.0.0.1;user id=sa;password="
Cookieless= "false"
Timeout= "20"
/>

<!--globalization
This section sets the globalization settings for the application.
-->
<globalization requestencoding= "Utf-8" responseencoding= "Utf-8"/>

</system.web>

</configuration>

Well, I believe that after reading the above introduction, the Web.config file must know very well. Here we go to the topic. In order to prevent users from not authenticated access to the site, our approach is that when the user does not pass the verification when clicking on any page will jump directly to the Login.aspx page, the specific code is as follows:

<authentication mode= "Forms" >
<forms name= "Yourauthcookie" loginurl= "Login.aspx"
protection= "All" path= "/"/>
</authentication>
<authorization>
<deny users= "?"/>
</authorization>
But this will create a problem, that is, if my site has some information can be arbitrary access to any user, such as site profiles, use instructions. If according to the above processing method does not let the user feel very troublesome, hehe, is not urgent, in the asp.net nature has the corresponding solution. The following code enables anonymous users to access the Test.aspx page:

<location path= "Test.aspx" >
<system.web>
<authorization>
<allow users= "?"/>
</authorization>
</system.web>
</location>

Solve the above two problems, I believe we must have the bottom of the heart. The following is the implementation of the Login.aspx page. Using C # and SQL Server2000, create a WebForm page and add the appropriate controls. The specific code is as follows:

<%@ Page language= "C #" codebehind= "Login.aspx.cs"
Autoeventwireup= "false" inherits= "Secure.login"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<title>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>
&LT;TD valign= "Top" align= "left" >
<asp:label id= "message" runat= "Server" forecolor= "#ff0000" >
</asp:label>
</td>
</tr>
<tr>
&LT;TD valign= "Top" align= "left" >
<b>E-mail:</b>
</td>
</tr>
<tr>
&LT;TD valign= "Top" align= "left" >
<asp:textbox id= "username" runat= "server" width= ">"
</asp:textbox>
</td>
</tr>
<tr>
&LT;TD valign= "Top" align= "left" >
<b>Password:</b>
</td>
</tr>
<tr>
&LT;TD valign= "Top" align= "left" >
<asp:textbox id= "Password" runat= "Server"
Width= "textmode=" "Password" >
</asp:textbox>
</td>
</tr>
<tr>
&LT;TD valign= "Top" align= "left" >
<asp:checkbox id= "Savelogin" runat= "Server"
text= "<b>save my login</b>" >
</asp:checkbox>
</td>
</tr>
<tr>
&LT;TD valign= ' top ' align= ' right ' >
<asp: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 start writing the Submit button event, which requires you to register the event first, as follows:

private void InitializeComponent ()
{
This.btnLogin.Click + = new System.Web.UI.ImageClickEventHandler (This.btnlogin_click);
.
.
.
}
After the event is registered, it is natural to write the event handler function:

private void Btnlogin_click (object sender, System.Web.UI.ImageClickEventArgs e)
{
Ccommondb sql = new Ccommondb ();
String redirect = "";

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!";
}
}
After reading the above code must want to ask Ccommondb is where the Dongdong, this is a class I wrote, used to handle the user login information, if the success of the relevant information to write session, cookies and SQL database, while jumping to the Default.aspx page. Specifically as follows:

CCommonDB.cs

Namespace Secure.components
{
public class Ccommondb:csql
{
Public ccommondb (): Base () {}

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;

Log the user in
Login (email, password, ref nloginid, ref Nlogintype);

if (Nloginid!= 0)//Success
{
Log the user in
System.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 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);

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 string. Empty;
}
}

<summary>
Verifies 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 ();

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;


Command.commandtype = CommandType.StoredProcedure;
Command.commandtext = "Glbl_login";
COMMAND.PARAMETERS.ADD (Paramlogin);
COMMAND.PARAMETERS.ADD (Parampassword);

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 type
Nloginid = Convert.ToInt32 (row["login_id"). ToString ());
Nlogintype = Convert.ToInt32 (row["login_type"). ToString ());
}
Else
{
Nloginid = 0;
Nlogintype = 0;
}
}
}

Abstract public class Csql
{
Private SqlConnection SqlConnection; Connection string
Private SqlCommand SqlCommand; Command
Private 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>
Access to our SQL command
</summary>
Protected SqlCommand Command
{
get {return sqlCommand;}
}

<summary>
Access to our data adapter
</summary>
Protected SqlDataAdapter Adapter
{
get {return SqlDataAdapter;}
}

<summary>
Makes sure that everything are 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 ();

if (Sqldataset!= null)
Sqldataset = new DataSet ();
}

<summary>
Runs our command and returns the dataset
</summary>
<returns>the Data set</returns>
Protected DataSet RunQuery ()
{
Sqldataadapter.selectcommand = Command;

Sqlconnection.open ();
Sqlconnection.close ();

Sqldataadapter.fill (Sqldataset);

return sqldataset;
}
}
}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.