Create a secure web site in ASP. NET

Source: Internet
Author: User
Tags set cookie
Previously, I used ASP, PHP, and JSP to write websites. Code Site security is always a headache. Although we have compiled user logon, registration, and verification pages, the effect is always unsatisfactory. Sometimes we have to use a large number of session variables to store the relevant information and implement defense everywhere. In the. NET environment, this problem can be easily solved. 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 debugging and compilation
Set compilation DEBUG = "true" to set the debug symbol (. PDB Information)
Insert to the compilation page. Because this will create and execute
Slow large file, so this value should be set to true only during debugging, and all other times
False. For more information, see
Debug ASP. NET files.
--
Compilation defaultlanguage = "VB" DEBUG = "true "/

! -- Custom error message
Set customerrors mode = "on" or "remoteonly" to enable custom error messages, or set it to "off" to disable custom error messages.
Add the error mark for each error to be processed.
--
Customerrors mode = "remoteonly "/

! -- Authentication
This section sets the applicationProgramAuthentication Policy. Possible modes are \ "Windows \",
\ "Forms \", \ "Passport \", and \ "None \"
--
Authentication mode = "Windows "/

! -- Authorization
This section sets the application Authorization Policy. Allow or deny user or role access
Application resources. Wildcard: "*" indicates anyone ,"? "Anonymous
(Unauthorized) user.
--
Authorization
Allow Users = "*"/! -- Allow all users --

! -- Allow users = "[comma-separated user list]"
Roles = "[list of roles separated by commas]"/
Deny users = "[comma-separated user list]"
Roles = "[list of roles separated by commas]"/
--
/Authorization

! -- Application-level tracking record
Application-level tracing enables tracing log output for each page in the application.
Set trace enabled = "true" to enable application tracking records. If pageoutput = "true ",
The trace information is displayed at the bottom of each page. Otherwise, you can
Go to the "trace. axd" page to view
Application tracing logs.
--
Trace enabled = "false" requestlimit = "10" pageoutput = "false" tracemode = "sortbytime" localonly = "true "/

! -- Session Status settings
By default, ASP. NET uses cookies to identify which requests belong to a specific session.
If the cookie is unavailable, you can trace the session by adding the session identifier to the URL.
To disable cookie, 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 global settings of the application.
--
Globalization requestencoding = "UTF-8" responseencoding = "UTF-8 "/

/System. Web

/Configuration

Well, I believe that after reading the above introduction, I will be very familiar with the Web. config file. Next we will go into the topic. To prevent users from accessing the site without verification, when a user does not pass the verification, clicking any page will directly jump to the login. ASPX page. The Code is as follows:

Authentication mode = "forms"
Forms name = "yourauthcookie" loginurl = "login. aspx"
Protection = "all" Path = "/"/
/Authentication
Authorization
Deny users = "? "/
/Authorization
However, this may cause a problem, that is, if some information on my site is accessible to any user at will, such as the site introduction and instructions for use. If the above processing method does not make the user feel very troublesome, haha, not in a hurry, there will naturally be a corresponding solution in ASP. NET. The following code allows anonymous users to access the test. ASPX page:

Location Path = "test. aspx"
System. Web
Authorization
Allow Users = "? "/
/Authorization
/System. Web
/Location

I have solved the above two problems. I believe you will have a thorough understanding. The following describes how to implement the login. ASPX page. Use C # and SQL Server2000 to create a webform page and add corresponding controls. The 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
Titlesecure site/Title
Meta content = "Microsoft Visual maxcompute 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" forecolor = "# ff0000"
/ASP: Label
/TD
/Tr
Tr
TD valign = "TOP" align = "left"
Be-mail:/B
/TD
/Tr
Tr
TD valign = "TOP" align = "left"
ASP: textbox id = "username" runat = "server" width = "120"
/ASP: textbox
/TD
/Tr
Tr
TD valign = "TOP" align = "left"
Bpassword:/B
/TD
/Tr
Tr
TD valign = "TOP" align = "left"
ASP: textbox id = "password" runat = "server"
Width = "120" textmode = "password"
/ASP: textbox
/TD
/Tr
Tr
TD valign = "TOP" align = "left"
ASP: checkbox id = "savelogin" runat = "server"
TEXT = "bsave my login/B"
/ASP: checkbox
/TD
/Tr
Tr
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 ready, write the submit button event. First, register the event. The Code is 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 processing 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, the reader must ask where ccommondb comes from. This is a class I have written to process user login information, if successful, the related information will be written to the session, cookie, and SQL database, and the information will be redirected to default. ASPX page. The details are 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; // connection string
Private sqlcommand; // command
Private sqldataadapter; // data adapter
Private dataset sqldataset; // data set

Public csql ()
{
Sqlconnection = new sqlconnection (configurationsettings. etettings ["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 is 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
/// Returnsthe 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.