Use the ASP.net framework to create a site login

Source: Internet
Author: User
Tags define config hash md5 relative resource sql injection root directory
. NET Framework |asp.net| creation

Originally the title should be, take advantage of. NET Framework Authoring security Web site.

This is a excerpt from MSDN, combined with my own experiences.

I saw a lot of friends are trying to write a site with landing features, the method is almost all to verify the user's login legal, and then send a verification of the cookie, or in the session to save information to facilitate tracking the next access authorization, in fact, these details of the operation. NET provides a very effective solution that frees you from cumbersome security validation, and although you may be very careful to define those pages that cannot be accessed by people without permission, there may be vulnerabilities that cannot be checked out to allow them to bypass security verification.


Okay, cut the crap. This article will introduce the following:
1. About Login verification and authorization
2. Use Forms Validation Mode
3. Access to Authorized resources
4. role-based Authorization


1. About Login verification and authorization
Many websites have login dialog boxes that allow users to authenticate in advance to provide them with personalized services. You can think of this process as two things happen: validation and authorization! The purpose of the login is to verify that the user requesting the login is legitimate, and authorization is to verify that the legitimate user decides whether to access or reject according to their permissions when requesting resources.
The above Web site itself provides the practice of dialog boxes. NET is called the Forms validation mode, which is followed by this validation pattern. In the previous ASP xujing or other programmers, to save legitimate user authentication, use in future access authorization, have to use write cookies or save information in the session method, Adding a bunch of cumbersome code to verify that the user has access to the page before it is loaded will not be able to display the content of the pages, but the most annoying thing is that adding the code to the authorization page makes it seem repetitive and tedious, and probably not the safest, There are some subtle ways that you can easily circumvent this validation, so many of the things programmers will do in the future is to modify the bugs that are found in the process. In. NET System.Web.Security provides some Web site security solutions, although the basic idea of verifying the legality and authorization of the user has not changed, but the authorization work has almost been given to the. NET Framework, and some of our code needs to authenticate the user legally and tell the framework that the user is legitimate.

2. Use Forms Validation Mode
To use the Forms validation mode, add the following configuration to the Web.config file in the site root directory: (note case sensitive)

<configuration>
<system.web>
<authentication mode= "Forms"/>
</system.web>
</configuration>

This will tell. NET that your site uses Forms validation mode. NET will not participate in validating the user's work, but will hand over this work to you to complete, you must write some code to authenticate the user legally, and reports to. NET user is legal ... NET will send a verification cookie to the user, followed by the visit. NET performs an authorized operation on the basis of this cookie.

For example, we placed two input text boxes txtUserName and Txtpassword in the Login.aspx interface and, in the database, saved the username username and password UserPassword, using the Btnlogin button's Click event to authenticate 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") + "'";
Execute a query to the database using a similar SQL statement above, and return the data if the user is legitimate.
if (...)//according to the conditions of the user is legal
{
The following statement tells. NET sends a verification cookie to the user:
System.Web.Security.FormsAuthentication.SetAuthCookie (UserID, False)
Response.Redirect ("afterlogin.aspx"); Navigate to the Post landing page
}
Else
{
User not valid, prompt for error message
}
}

In the above code,
TxtUserName.Text.Replace ("'", "_") replaces single quotes in the text entered by the user with an underscore to prevent SQL injection attacks.
System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile (txtPassword.Text, "MD5") Method converts the txtPassword.Text to a MD5 hash value, noting that, when the user registers, the same method converts the registration password that it entered into a hash value stored in the database, where the hash value entered by the user is compared to determine whether the user is legitimate. Do not store sensitive text messages in the database in plaintext at any time. With MD5 encryption, even if the ciphertext is intercepted, the attacker still cannot get the real password.

When confirming that user authentication is legitimate, call the System.Web.Security.FormsAuthentication.SetAuthCookie (UserID, False) method and send a verification cookie, which passes two arguments. One is on behalf of the user's logo, in general, the next confirmation of the user's unique identity is obtained from the database UserID. The second argument tells. NET is written to a persistent cookie, if true, the cookie will persist and the next time the user accesses it, the cookie still exists (which is equivalent to remembering the user and can provide a checkbox for the user to decide whether to continue the cookie). Once a cookie has been sent, the jump statement can be invoked to jump to the specified place.

There is another way: Web.Security.FormsAuthentication.RedirectFromLoginPage (string UserName, bool); Cookies will be sent, and jumps to the specified page based on the passed ReturnUrl parameter (equivalent to one step above two steps). So login.aspx implicitly can pass ReturnUrl, and without this parameter, this method jumps the user to the Default.aspx page.

3. Access to Authorized resources
Once the user is validated, the next thing to do is to authorize them to access the resources requested by the user. Back in the Web.config file, you can use Web.config in any directory on your Web site, and their settings are passed on by inheritance.
For example, when a page is stored in the users directory that can be accessed after the user logs on, a Web.config file is created in this directory, which reads as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<system.web>
<!--authorization
This section sets the authorization policy for the application. You can allow or deny access to different users or roles
Application resources. Wildcard: "*" means any person, "?" means anonymity
(unauthenticated) user.
-->
<authorization>
<deny users= "?"/>
</authorization>
</system.web>
</configuration>

In this context, deny users= "?" will tell. NET that this directory denies anonymous users access, which is the unauthenticated user. When a user attempts to request a resource in this directory, it is redirected to the Login.aspx page, requesting a login. cannot be accessed without landing.

The above directory is defined only, programmers do not have to add any code on the page, you can fully implement the authorization scheme.
Of course, this directory-only authorization configuration may sometimes be inflexible, so. NET also provides the location configuration section, which allows you to define authorization for a specified resource:
<configuration>
<location path= "Userabc.aspx" >
<system.web>
<authorization>
<allow users= "A,b,c"/>
</authorization>
</system.web>
</location>
</configuration>

Where path is the resource relative path.

If that's not flexible enough, then. NET also provides the methods used in code, ASP. NET page globally implicitly has a read-only user object, By obtaining the User.Identity.IsAuthenticated property, you can detect whether the user is authenticated (that is, whether it is logged in), and the User.Identity.Name property obtains the user's name, which is the userid passed in the SetAuthCookie method at validation.

4. role-based Authorization
The user authentication described above can only be done in two cases where the user can authorize access to the resource through authentication, or the user does not pass validation and cannot access the resource that requires authorization. But even the authenticated users may need to make a further distinction between the permissions they hold. For example, ordinary users and administrators also need to verify that the pass, but ordinary users are obviously not able to access the Administration page, and administrators can. In the face of this situation,. NET can use a role-based authorization model.
The rationale is that once the user verifies the legality, they are assigned roles, the user can make one or more roles, and the resource's authorization is role-oriented, so that different permissions can be granted for different roles, and users without a certain role type attempting to access resources that require such a role will be rejected.
When the Web site begins to accept user requests, accompanied with authentication, the Application_AuthenticateRequest event is fired, and code is written in the Global.asax file to respond to this event. The assignment of roles needs to be done here again.

public void Application_AuthenticateRequest (object sender, EventArgs e)
{
if (this. request.isauthenticated)
{
This simplifies the operation by obtaining role information from the database to construct the Rolesstrarr array. As an example, we assign an administrator role to a user other than a
String[] Rolesstrarr;
if (this. Context.User.Identity.Name = "a")
{
Rolesstrarr = new string[]{"Normal User"};
}
Else
{
Rolesstrarr = new string[]{"Normal user", "admin"};
}
This. Context.User = new System.Security.Principal.GenericPrincipal (this. User.Identity, Rolesstrarr);
}
}

The above code is clear, so don't repeat it. Although there is a user object on the global, only the user object in the context contexts can be written. We call the System.Security.Principal.GenericPrincipal method to add a role to the original user object based on it. The role column represents an array of strings.

Once a user is granted access to a role, access to different roles can be configured in web.config. For example, within the admin admin directory

<configuration>
<location path= "Userabc.aspx" >
<system.web>
<authorization>
<allow roles= "admin"/>
<deny users= "*"/>
</authorization>
</system.web>
</location>
</configuration>

The above configuration allows only administrator roles to be authorized. The resource is accessed by default by anyone, so adding the <deny users= "*"/> below indicates rejection of any user.

Note that regardless of the role or access to a user-specified resource, they are separated by a half-width comma for multiple roles or for reading resources. Similarly, you can configure the specified resource instead of the entire directory using the method described above.

The global user object provides a method IsInRole (string rolename) method to detect whether a user has a role in code. If he owns this role, it returns true.


Postscript
. NET provides a complete security solution, which is an exciting new feature relative to the ASP. Just a lot of people may not be able to skillfully use, and most sadly, many books do not even have any description of this, even the concept is not. This makes people very skeptical about the editor's level.
First of all, or in the continuous practice of the process to understand and experience. NET, in fact, the best teacher should be MSDN, to the forum to post users, I try to recommend to go to the MSDN information, MSDN in addition to teach you how to write code, in fact, he taught you also have very good ideas and the overall concept. As long as you learn to use, no these books can be. From writing the first line of code to the present, except for an introductory book, other resources are available on MSDN or online, and in each project. Although it seems that the Enlightenment book does not have a very comprehensive account of these things.



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.