ASP. NET security questions-Forms authentication (later)-Practice

Source: Internet
Author: User
Tags connectionstrings

ASP. NET security question-forms verification practice

Through previous articlesArticleI believe that you have a certain understanding of forms verification and understand the concepts of identity, iprincipal, and Bill. The previous website has not linked verification with the database. This article will explain from this aspect, usingCodeTo demonstrate! In addition, some role authorization issues are also involved in the code!
Today's topic is as follows:

Verification process description
Database preparation
Code Writing

Links to articles:

ASP. NET development security issues

ASP. NET security issues-creating secure Web Applications

ASP. NET security question-ASP. NET security architecture

ASP. NET security question -- ASP. Net Security Architecture -- How to Implement. Net Security

ASP. Net Security Question-Authentication and Identity Authentication Module in ASP. NET lifecycle

ASP. NET security question-detailed introduction to Forms authentication (Part 1)

ASP. NET security question-froms verification details (Part 1)

ASP. NET security questions-Forms authentication (later)-Practice

ASP. Net Security Question -- authorization question in ASP. NET (previous article)

Verification process description

First, let's assume that the user has opened our homepage default. aspx, but some resources can only be viewed by the login user. If the user wants to view these resources, he needs to log on. This user already has an account. (The main topic in this article is identity authentication. As for how to create a user account, we don't care about it. There are many methods, such as inserting a database directly !)
Let's talk about some of our processes:
1.User Logon: Enter the user name and password in the input box.
2. Click "Log on" to check whether the user exists in the database.
3If yes, the server code creates an authentication ticket, stores it in the cookie, and sends it to the browser of the client.
4. If the user already has a verified cookie, the page will jump to the page previously requested by the user

Database preparation

Next we will start to detail:
First of all, we must first create a database, and then create a user information table named login. In this table, we create three fields: username, userpassword, userrole (you can create more fields. I will just demonstrate it here and you can expand it ). as for the data in the table, you can insert a few items at will!
Code Writing
Because we often need to verify the user, we write the user verification code as a method in the helpers. CS class under the app_code directory.
The Code is as follows:

Verification Code
Public Static BoolValidateuser (StringUsername,StringPassword)
Sqlconnection con =   New Sqlconnection ();
Con. connectionstring =
Configurationmanager. connectionstrings ["myconnectionstring"]. connectionstring;

sqlcommand com = New sqlcommand ();
COM. connection = con;
COM. commandtext = " select count ( * ) from users where username = @ username and userpassword = @ password";

Com. Parameters. addwithvalue ("@ username", username );
Com. Parameters. addwithvalue ("@ Password", password );
Con. open ();

IntCNT=(Int) COM. executescalar ();
Con. Close ();

Return (CNT >   0 );
} Then we will create a login page login. aspx, and put two textbox on the page for the user to enter the user name and password respectively. Put a button to log on. Return to helpers. CS and add another method to obtain the role of the User: Code
Public   Static   String Getroleforuser ( String Username)
// Create Link
Sqlconnection con =   New Sqlconnection ();
Con. connectionstring =
Configurationmanager. connectionstrings ["myconnectionstring"]. connectionstring;

sqlcommand com = New sqlcommand ();
COM. connection = con;

// RUN
COM. commandtext = " select userole m users where username = @ username;
COM. parameters. addwithvalue ("@ username", username);
con. open ();

//Returned results
StringUserrole=(String) COM. executescalar ();

Con. Close ();


To enable Forms authentication, we also get the configuration in the web. config file, as shown below: < Authentication Mode = "Forms">
<Forms name = ". Mycookie" Path = "/" Loginurl = "Login. aspx" Protection = "All"
Timeout = "40" />
</ Authentication > Anonymous users are not allowed to access our website: < Authorization >
< Deny Users = "?" />
</Authorization > Then we started to write code under the login. aspx login button: The basic idea is as follows: 1. Verify that the user exists, 2 . If it exists, obtain the role of the user at the same time. 3. Create an authentication ticket and cookie, and add comments to the Code sent to the browser of the client. Based on the previous Foundation, we believe that the following code is correct. Code
Protected   Void Logincallback ( Object Sender, eventargs E)
If (Helpers. validateuser (username. Text, password. Text ))
// Get User Role
String Rolenames = Helpers. getrolesforuser (username. Text );

// Create authentication ticket
Formsauthenticationticket ticket =   New Formsauthenticationticket ( 1 ,
Username. Text, datetime. Now, datetime. Now. addseconds ( 40 ), False , Roles );

//Encrypted ticket
StringEncryptedticket=Formsauthentication. Encrypt (ticket );

// Create a new cookie
Httpcookie =   New Httpcookie (formsauthentication. formscookiename );

// Put encrypted ticket information into cookie
Cookie. Value = Encryptedticket;

//Add cookie to response stream
Response. Cookies. Add (cookie );

//Send cookie to client
Response. Redirect (formsauthentication. getredirecturl (username. Text,False),True);

}Now, if we enter the correct user name and password, we will have the authentication cookie in our browser, and now our page will be immediately taken from the original login. aspx switched to default. the ASPX page is now in progress, and we need to analyze this process in our minds. In login. aspx switched to default. in the process of ASPX page jump, we are actually requesting default. ASPX page. There is no difference in the previous request process. It also requires ASP. net, but this time our browser already has authentication cookies, Asp.. NET is being processed at runtime. when processing the application_authenticaterequest event, we need to parse our cookie. In fact, before we log on, we resolved the cookie in the Event code, but at that time we did not find the cookie. In the code of the application_authenticaterequest event, the cookie is parsed, the user's identity is identified, and the user's identity information is saved as follows: Code

code highlighting produced by actipro codehighlighter (freeware)

--> Code
void application_authenticaterequest ( Object sender, eventargs E)
{< br> httpapplication app = (httpapplication) sender;

//Obtain authentication cookies
Httpcookie=Request. Cookies [formsauthentication. formscookiename];

If(Cookie! = Null)
StringEncryptedticket=Cookie. value;

// decrypt the ticket information in the cookie
formsauthenticationticket ticket =
formsauthentication. decrypt (encryptedticket);

// get user role information
string [] roles = New string [] {ticket. userdata. tostring () };

// create a user ID
formsidentity identity = New formsidentity (ticket );

//Create a user's Subject Information
System. Security. Principal. genericprincipal user=
NewSystem. Security. Principal. genericprincipal (identity, roles );
App. Context. User=User;


We can see the last line of code: App. Context. User = user; stores the user's identity and role information in the user attribute. On the page, we can use the following method to determine whether the user has logged on:   If (Page. User. Identity. isauthenticated)
} Use the following method to determine whether a user belongs to a role: If (Page. User. isinrole ( " Admin " )
} In fact, the identity and iprincipal concepts we mentioned earlier are related. If you are not clear about them, please refer to the previous article! The Code has been written here today, and the issue of identity authentication has to be completed. There is still a problem that is not described: Customize authentication and develop custom httpmodule. Subsequent articles Authorization . Thank you for your support!
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: 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.