Create website login using ASP. NET Framework

Source: Internet
Author: User
Tags md5 hash

The title should have been to use the. NET Framework to create a secure website.

This was excerpted from msdn and combined with my own experiences.

I have seen many of my friends trying to write a website with such a function as login. The method is almost all to verify that the user's login is legal, and then send a cookie indicating authentication, or you can save the information in the session to track the next access authorization. In fact, these detailed operations ,. NET provides a very effective solution to free you from tedious security verification. Moreover, although you may be very careful to define that pages cannot be accessed by unauthorized users, there may be some vulnerabilities that cannot be checked out so that they can skip security verification.

This article will introduce the following content:
1. login verification and authorization
2. Use Forms authentication mode
3. Authorize Resource Access
4. Role-based authorization

1. login verification and authorization
Many websites have Login Dialog Boxes for pre-registered users to verify, so as to provide them with personalized services. We can think of this process as the occurrence of two things: verification and authorization! The role of login is to verify whether the user requesting login is legal, and authorization is to verify whether a valid user can access or reject resources based on their permissions.
The preceding dialog box provided by the website itself is called the forms authentication mode in. net. The following describes the Authentication mode. In the past, ASP programmers or other programmers had to write cookies or save information in sessions to save the authentication of Valid users for future access authorization, add a bunch of tedious code before loading the page to verify whether the user has access permissions. Otherwise, the page content cannot be displayed, the most annoying thing is that adding the code on the Authorization page is repetitive and cumbersome, and may not be the safest. Some concealed methods may easily bypass such verification, therefore, the programmer will do a lot of work in the future, that is, to modify the code and block the vulnerabilities discovered during the running process. In. net System. web. security provides some website security solutions. Although the basic idea of user authentication is not changed, the authorization work has almost been handed over.. NET Framework. We need to verify that the user is valid and notify the user of the framework.

2. Use Forms authentication mode
To enable the forms authentication mode, add the following configuration in the web. config file under the root directory of the Website: (case sensitive)

<Configuration>
<System. Web>
<Authentication mode = "forms"/>
</System. Web>
</Configuration>

This will tell.. net, your website uses the forms authentication mode ,.. NET will not participate in user verification, but will hand over this work to you to complete, you must write some code to verify that the user is legal, and report.. Net users are legal .. . NET will send a verification cookie to the user, and then access. NET will perform the authorized operation based on the cookie.

For example, we placed two text boxes txtusername and txtpassword on the login. aspx interface for receiving input. in the database, we saved the username and password userpassword, and used the Click Event of the btnlogin button to verify the user:

Private void btnlogin_click (Object sender, eventargs E)
{
String SQL = "select userid from users where username = '" + txtusername. text. replace ("'", "_") + "' and userpassword = '" + system. web. security. formsauthentication. hashpasswordforstoringinconfigfile (txtpassword. text, "MD5") + "'";
// Use an SQL statement similar to the above to query the database. If the user is valid, data is returned.
If (...) // determine that the user is legal based on the conditions
{
// The following statement tells. Net to send a verification cookie to the user:
System. Web. Security. formsauthentication. setauthcookie (userid, false)
Response. Redirect ("afterlogin. aspx"); // go to the post-login page.
}
Else
{
// The user is invalid and an error message is displayed.
}
}

In the above Code,
Txtusername. Text. Replace ("'", "_") replaces the single quotation marks in the text you enter with underscores to prevent SQL injection attacks.
System. web. security. formsauthentication. hashpasswordforstoringinconfigfile (txtpassword. text, "MD5. text is converted to MD5 hash values. Note that when a user registers, the user also uses this method to convert the entered registration password to hash values and store them in the database, the hash value entered by the user is compared to determine whether the user is valid. Do not store sensitive text information in the database in plain text at any time. Through MD5 encryption, even if the ciphertext is intercepted, attackers still cannot obtain the real password.

When you confirm that the user authentication is valid, call system. web. security. formsauthentication. setauthcookie (userid, false) method, which sends authentication cookies. This method passes two parameters, one representing the user's ID. Generally, the unique identity of the user is the userid obtained from the database. The second parameter tells. net whether to write a continuous cookie. If it is true, the cookie will be sustained. The next time the user accesses the cookie, the cookie will still exist (equivalent to remembering the user, you can provide such a check box for users to decide whether or not to continue cookies ). After sending the cookie, you can call the jump statement to jump to the specified place.

There is another method: Web. security. formsauthentication. redirectfromloginpage (string username, bool); the cookie is sent, and the specified page is redirected Based on the passed returnurl parameter (equivalent to combining the above two steps as one step ). Therefore, login. aspx can implicitly pass returnurl. If this parameter is not provided, this method redirects the user to the default. aspx page.

3. Authorize Resource Access
Once the user is verified to be valid, the next thing to do is to authorize the user to access the resources requested by the user. Return to the Web. config file and use web. config in any directory of the website. Their settings are inherited.
For example, if all the pages in the users directory are accessible only after the user logs on, create a web. config file in this directory with the following content:

<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<System. Web>
<! -- Authorization
This section sets the application Authorization Policy. Allow or Deny Access From different users or roles
Application resources. Wildcard: "*" indicates anyone ,"? "Anonymous
(Unauthenticated) user.
-->
<Authorization>
<Deny users = "? "/>
</Authorization>
</System. Web>
</Configuration>

Deny users = "? "Will tell. Net that this directory rejects access from anonymous users, that is, unauthenticated users. When a user tries to request resources in this directory, the user will be redirected to the login. ASPX page again, requiring login. If you do not log on, you cannot access the service.

The above only defines the directory. programmers can complete the authorization scheme without adding any code on the page.
Of course, this type of authorization configuration for directories may sometimes be inflexible. Therefore,. Net also provides the location configuration section to define authorization for specified resources:
<Configuration>
<Location Path = "userabc. aspx">
<System. Web>
<Authorization>
<Allow users = "a, B, c"/>
</Authorization>
</System. Web>
</Location>
</Configuration>

Path indicates the relative resource path.

If this is not flexible enough ,. net also provides methods used in code, Asp. the. NET page contains a read-only user object. identity. isauthenticated attribute to check whether the user is verified (that is, whether the user is logged on), user. identity. the name attribute can obtain the user's name, that is, the userid passed in the setauthcookie method during verification.

4. Role-based authorization
The user authentication described above is only possible in two cases: users can access resources through authentication, authorization, or users cannot access resources that need authorization. However, even users who pass the verification may need to further differentiate their permissions. For example, a common user and an administrator need to pass the verification, but the common user obviously cannot access the management page, but the administrator can. In this case,. Net can use a role-based authorization model.
The basic principle is that once the user authentication is valid, they will be assigned a role, the user can make one or more roles, and the resource authorization is role-oriented. In this way, for different roles, different permissions can be granted. Users without a certain role type attempt to access resources that require such a role will be denied.
When the website begins to accept user requests, verification will trigger the application_authenticaterequest event and write code in the global. asax file to respond to this event. The assignment of roles needs to be done here.

Public void application_authenticaterequest (Object sender, eventargs E)
{
If (this. Request. isauthenticated)
{
// The operation is simplified here. role information can be obtained from the database to construct the rolesstrarr array. As an example, we assign an administrator role to users other than.
String [] rolesstrarr;
If (this. Context. User. Identity. Name = "")
{
Rolesstrarr = new string [] {"normal user "};
}
Else
{
Rolesstrarr = new string [] {"normal user", "Administrator "};
}
This. Context. User = new system. Security. Principal. genericprincipal (this. User. Identity, rolesstrarr );
}
}

The above code is clear and clear, so we will not repeat it here. Although a user object exists globally, only the user object in the context can be written. We call system. security. principal. genericprincipal method, which adds a role to the original user object. The role column represents a string array.

Once a user is granted an access role, you can configure access for different roles in Web. config. For example, in the Admin directory of the Administrator

<Configuration>
<Location Path = "userabc. aspx">
<System. Web>
<Authorization>
<Allow roles = "Administrator"/>
<Deny users = "*"/>
</Authorization>
</System. Web>
</Location>
</Configuration>

The preceding configuration only allows the administrator role to be authorized. By default, resources are accessible to anyone. Therefore, you must add <deny users = "*"/> below to deny access to any user.

Note: Whether you access a role or a specified resource, if you have multiple roles or read resources, they are separated by commas. You can also use the method described above to configure the specified resource instead of the entire directory.

The global user object provides the isinrole (string rolename) method to detect whether a user has a certain role in the code. True is returned if the user has this role.

Postscript
. NET provides a complete security solution. Compared with ASP, this is an exciting new feature. However, many people may not be able to use it skillfully, and the most painful thing is that many books do not even have any descriptions in this aspect, or even have no concept. This makes people very skeptical about the editor's level.
First of all, we should continue to understand and understand in the process of practice. net, in fact, the best teacher should be msdn. Users who post on the Forum, I suggest reading the msdn materials whenever possible. Besides, msdn will teach you how to write code, in fact, he taught you excellent ideas and overall concepts. As long as you learn to use these books, you can. From the first line of code writing to the present, apart from a book, other resources are found on msdn or the Internet, and there are experiences in every project. Although it seems that the book does not fully describe these things.

Well, I hope you will see some gains. Limited to my level. errors are inevitable. please correct me!

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.