How to Implement form authentication login in ASP. NET

Source: Internet
Author: User

How to use form Authentication

 

ASP. NET security authentication. There are four authentication modes: "Windows", "form", "Passport", and "NONE. "Windows" and "NONE" do not play a protection role and are not recommended. I have never used "Passport", alas ...... So I have to talk about "form" certification. I plan to divide it into three parts:

Part 1 -- How to Implement from authentication;

Part 2: Practical Application of form authentication;

Part 3: Single Sign on)

Part 1 how to use form Authentication

1. Create a test project

For better description, it is necessary to create a test project ("formtest" for the time being), which contains three pages (default. aspx, login. aspx, userinfo. aspx ). What? No one will create a project or add a page? What should I do? I think it's okay: drag it out, call it back, learn from kindergarten ......

2. modify web. config

1. Double-click Web. config in the project (No, cannot find pp)

2. Find the following text <Authentication mode = "Windows"/> and change it:

<Authentication mode = "forms">

<Forms loginurl = "login. aspx" name = ". aspxauth"> </Forms>

</Authentication>

3. Replace <authorization> <allow users = "*"/> </authorization>

<Authorization> <deny users = "? "> </Deny> </authorization>

There is nothing to say here, just copy it. However, some people may make a mistake as follows:

<Authentication mode = "forms">

<Forms loginurl = "login. aspx" name = ". apsx"> </Forms>

<Deny users = "? "> </Deny>

</Authentication>

If you want to ask who used <deny users = "? "> </Deny> put in <authentication>, I will be honored to tell you that it was me n years ago: <authentication> and <authorization> both start with the auth letter and end with the ation. Why? I think they are a group of English words that cannot be memorized ......

3. Write. CS code-Logon and exit

1. logon code:

A. Introduced in books

Private void btn_login_click (Object sender, system. eventargs E)

{

If (this. txt_username.text = "admin" & this. txt_password.text = "123456 ")

{

System. Web. Security. formsauthentication. redirectfromloginpage (this. txt_username.text, false );

}

}

B. I have been searching for N for a long time.

Private void btn_login_click (Object sender, system. eventargs E)

{
If (this. txt_username.text = "admin" & this. txt_password.text = "123456 ")
{

System. Web. Security. formsauthentication. setauthcookie (this. txt_username.text, false );

Response. Redirect ("default. aspx ");

}
}

The two types of cookies can be issued after verification, that is, they pass verification. difference:

Method A) returns the request page after verification, which is commonly known as "from where to where ". For example, if you enter http: // localhost/formtest/userinfo. aspx directly in the IE address bar before logging on, the user will see login. aspx? Returnurl = userinfo. aspx. After the user name and password are entered, the system returns the corresponding page based on the value of "returnurl ".

Method B) two steps are taken: after the verification is passed, the cookie is directly issued, and the jump page will be designated by the programmer. This method is mostly used in the system where default. aspx uses the framework structure.

2. Exit code:

Private void btn_logout_click (Object sender, system. eventargs E)
{

System. Web. Security. formsauthentication. signout ();

}

Iv. How to determine whether the verification is successful and obtain the verified user information

Sometimes, you need to determine whether the user has logged on to the same page and then display different la S. Some people like to use the session to judge, and I do not oppose this kind of practice. Here I just want to tell you there is another method and read the following code:

If (user. Identity. isauthenticated)
{

// You have passed the verification. Do you know what to do?

}

User. identity also has two attributes: authenticationtype (authentication type) and name (User Name). Note that the name attribute is the user. identity. name will get, when the verification passes (redirectfromloginpage or setauthcookie), we bring the first parameter This. txt_username.text. This parameter is very important and related to various types ...... In all kinds of situations, let's talk about this and break it down ......
Flexible Use of deny and allow in form authentication and Protection of. HTM files

Part 2 practical application of form Authentication

 

Scope of application of Web. config

When you create a project, vs. Net creates a fixed web. config file in the project root directory. In addition to the project root directory, you can also create web. config in any directory. The condition is that application-level nodes can only appear in Web. config in the root directory. I am not sure about the application-level nodes. I didn't invented my computer. I didn't create Microsoft, and C # was not my final idea. I don't know anything about the gods, so I don't know it's normal. Even so, as long as it does not report an error, it is correct.

For the scope of the web. config settings, remember the following two points:

1. Web. config settings apply to all files in the directory and all the objects in its subdirectories (inherit: Sub-parent with parent name)

2. The web. config settings under the subdirectory will overwrite the settings inherited by the parent directory (overwrite: the county officials are not as competent as they are now)

I would like to ask you a question: is there a configuration file that is more effective than the root directory web. config? After reading the third part, we will be able to understand the problem.

6. Learn to reject and use allow

Go back to the test project "formtest" we created in the first round. To verify the project, we have to have a user name and password according to international practice. So, are these users created by the Administrator in the database, or are these users registered and reviewed by the administrator. As long as it is not an ordinary idiot, we all know that we should select the latter. Don't you mention that some of my company's projects are actually managed by the Administrator to connect to the database to create an account. It's a special dumb. Let's leave him alone, add two pages honestly-register the page (register. aspx) and audit page (auditing. aspx ).

The problem is coming to the fore. When you try register. aspx and want to access it, you suddenly feel that something is wrong. Why did you go back to the login page? Take a closer look at the url. Is it login. aspx? Returnurl = register. aspx. What should I do? The user can access the registration page without an account? (This is a nonsense. If you have an account, you can register it .) I often say to my colleagues, "the way is people come up !!"

1. Create a directory named public to store some public files, such as perpetual calendar and scripts ......

2. In Solution Explorer, right-click the directory public and add a web. config

3. delete all the preceding web. config content. Leave the following only:

<? XML version = "1.0" encoding = "UTF-8"?>

<Configuration>

<System. Web>

<Authorization> <allow users = "*"/> </authorization>

</System. Web>

</Configuration>

It's not easy to get started. According to the "Overwrite" principle, we know that the above Web. config will replace the <authorization> node settings in the root directory web. config, that is:

<Allow users = "*"/> replace <deny users = "? "> </Deny>

Note: "allow" allows meaning; "*" indicates all users;

"Deny": "?" Indicates an anonymous user;

Therefore, files in the public directory are accessible to all users, including unauthenticated users. Drag register. aspx in and no one will stop you from browsing.

In addition to the registration page, we also mention an audit page (auditing. aspx), audit permissions are generally in the hands of administrators or supervisors, and do not want others to browse this page (truth is often in the hands of a few people, this is also impossible), what should I do? "The way is people come up with something ...... Create an Administrator directory named managesys, and add another Web. config under this directory. The content is as follows:

<? XML version = "1.0" encoding = "UTF-8"?>

<Configuration>

<System. Web>

<Authorization>

<Allow users = "admin"/>

<Deny users = "*"/>

</Authorization>

</System. Web>

</Configuration>

 

System. Web. Security. formsauthentication. setauthcookie (this. txt_username.text, false); // The cookie is issued after verification.

I have previously stressed that the first parameter is very important. To what extent? Speaking of this, I am afraid everyone on Earth knows it-it is the basis of allow and deny. Assume that you enter "admin", that is, this. txt_username.text = "admin"; then, after entering the system, he will be able to access the webpage under the managesys directory, and all other idle people will be rejected.

From
Http://www.rjjd.com/bbs/simple/index.php? T17819.html

1: Add form authentication in Web. config;
 
<Authentication mode = "forms">
<Forms name = "auth" loginurl = "index. aspx" timeout = "30"> </Forms>
</Authentication>
<Authorization>
<Deny users = "? "/>
</Authorization>
2: If a registration page exists, anonymous users should also be allowed to call the registration page for registration;
The following code should be between <configuration> <system. Web> and not between <system. Web>... </system. Web>;
---------------- Indicates that anonymous users are allowed to access the userreg. ASPX page.
<Location Path = "userreg. aspx">
<System. Web>
<Authorization>
<Allow users = "? "/>
</Authorization>
</System. Web>
</Location>
3. After Successful Logon, you must create an authentication ticket to indicate that the authenticated user has been valid;

If (LOGIN successful)

System. Web. Security. formsauthentication. setauthcookie (user name, false );

1. Use Forms verification to store user-defined information

The internal mechanism of Forms authentication is to encrypt user data and save it in a cookie-based ticket formsauthenticationticket. Because it is specially encrypted, it should be safer. In addition to using this bill to store your own information,. Net also leaves a place for the user to control freely. This is the userdata to be mentioned now.

Userdata can be used to store string-type information and enjoy the encryption protection provided by Forms authentication. When we need this information, we can also get it through a simple get method, taking into account the security and ease of use, it is useful to save some necessary sensitive information.

The following shows how to use userdata. An example is provided.

// Create a new ticket and record the Client IP address to ticket's userdata
Formsauthenticationticket ticket = new formsauthenticationticket (
1, username. Text, datetime. Now, datetime. Now. addminutes (30 ),
False, request. userhostaddress );
// Encrypt the ticket
String authticket = formsauthentication. Encrypt (ticket );
// Save the encrypted ticket as a cookie
Httpcookie coo = new httpcookie (formsauthentication. formscookiename, authticket );
// Use the new cookie with userdata added
Response. Cookies. Add (COO );

The following is the method signature of one of the reloads of the formsauthenticationticket constructor.
Public formsauthenticationticket (
Int version,
String name,
Datetime issuedate,
Datetime expiration,
Bool ispersistent,
String userdata
);

Parameters
Version
Version number.
Name
The username associated with the authentication ticket.
Issuedate
The time when the cookie is sent.
Expiration
The expiration date of the cookie.
Ispersistent
If the cookie is persistent, it is true; otherwise, it is false.
Userdata
User-Defined data stored in cookies

Using userdata is also very simple. The ticket attribute of formsidentity provides access to the current ticket. After obtaining the ticket, you can use the userdata attribute to access the saved information, which is decrypted.
(System. Web. Security. formsidentity) This. Context. User. Identity). Ticket. userdata

The following is a specific application.

Because Forms authentication is carried out through cookies, it needs to pass a ticket for work. Although the ticket is encrypted and the content is invisible, it cannot prevent others from using the ticket with a fake identity (just as we can use others' keys to unlock others' locks ), it is common that users of different IP addresses intercept the ticket through insecure channels and then use it for activities outside the security scope.

One way to solve this problem is to use SSL to transmit information.

But what if I cannot use SSL? We can determine whether the IP address matches the ticket. If the requested IP address is the IP address that generates the ticket for the first time, there is no problem; otherwise, the ticket will be destroyed.

Therefore, we need to save the user's IP address when processing the login at the beginning, so that we can verify whether the IP address of the subsequent request is the same as the initial IP Address at any time in future requests. The best place to store this sensitive IP address is userdata, and the verification time is when the authenticaterequest event occurs, that is, global. aspx. CS defines the application_authenticaterequest method for processing this event.

The preceding example actually saves the user IP address to userdata. The verification process is as follows.

If (this. Request. isauthenticated)
{
If (system. Web. Security. formsidentity) This. Context. User. Identity). Ticket. userdata! = This. Request. userhostaddress)
{
System. Security. Principal. genericidentity gi = new system. Security. Principal. genericidentity ("","");
String [] rolesi = {};
System. Security. Principal. genericprincipal GPI = new system. Security. Principal. genericprincipal (GI, rolesi );
This. Context. User = GPI;
}
}

The genericidentity and roles empty for genericprincipal invalidate the ticket, which forces the user to log on again. To test this method, you can first change the conditions to equal, to see how it works :)

This method also has shortcomings, specifically:

1. users using the same proxy will have the same IP address, so they cannot prevent such counterfeit attacks.

2. If the user uses a dynamic IP address, the normal user may be forcibly destroyed by us. But in general, this method is quite feasible.

2. Use security features with forms authentication for security operations.

Principalpermissionattribute can be used with forms authentication for role-based or user-based security authentication. This feature cannot be used at the Assembly level. It can be a class or a specific method. Let's look at a simple example.

[Principalpermission (securityaction. Demand, user = "notus")]
Public class test: basepage
{
Private void page_load (Object sender, system. eventargs E)
{
Try
{
This. sayhello ();
This. sayhello2 ();
}
Catch (exception ex)
{
Response. Write (ex. tostring ());
}
}

Private void sayhello ()
{
Response. Write ("Hello world! ");
}

Private void sayhello2 ()
{
Response. Write ("Hello principalpermissionattribute! ");
}

 

# Code generated by region web Form Designer
Override protected void oninit (eventargs E)
{
//
// Codegen: This call is required by the ASP. NET web form designer.
//
Initializecomponent ();
Base. oninit (E );
}

/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
Private void initializecomponent ()
{
This. Load + = new system. eventhandler (this. page_load );
}
# Endregion

}

Note that this example applies to the entire class at the beginning. It is generated and executed. If the current user is not notus, an exception system. Security. securityexception will occur, prompting that the request for the subject permission fails. Otherwise, you can access the service smoothly and output two Hello world !, Note that there are two. The current security scope is the entire class.

Next, let's change the scope of the feature. Move the feature declaration to the sayhello2 method and run it after re-compilation. Then, the system. Security. securityexception is thrown after the program runs to the sayhello2 method. This shows that the scope of security is now reduced to the method level.

This feature allows you to set user and role for user and role-based security protection. In addition, the first parameter used is the securityaction enumeration, which sets a specific protection level or measure. The demand we use now requires that all advanced callers in the call stack have been granted the permissions specified by the current permission object.

The following is an example from msdn:

Example

The following example shows how to use principalpermission to claim that the current user is Bob and belongs to the supervisor role.
[Principalpermissionattribute (securityaction. Demand, name = "Bob ",
Role = "supervisor")] the following example shows how to require the identity of the current user to be Bob, which is irrelevant to the role Member conditions.
[Principalpermissionattribute (securityaction. Demand, name = "Bob")]
The following example shows how to verify the identity of a user only.
[Principalpermissionattribute (securityaction. Demand, Authenticated = true)]

Here, the user and role can be integrated with forms verification. Accordingly, we can use principalpermissionattribute in some important classes or methods, to arm your program to the home.

In fact, this feature has far more functions than this. For more details, refer to msdn.

Or:
1. Configure the Web. config file

Set to form authentication:
<Authentication mode = "forms">
<Forms name = "oursnet" loginurl = "login. aspx" timeout = "10"/>
</Authentication>
Where:
Name: determines the cookie name used for user authentication.
Loginurl: redirected page when the user does not log on
Timeout: time-out period, in minutes

Anonymous Logon not allowed
<Authorization>
<! -- Allow all users -->
<Deny 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>
Where:
Users: indicates the list of users that are prohibited from accessing resources. The wildcard "?" is used. "Deny anonymous user access. If" * "is used, all users are denied access.

2. Add the logon successful code:

Session. Contents ["username"] = txtuser. text;
Formsauthentication. redirectfromloginpage (txtuser. Text, false );
Response. Redirect ("index. aspx ");

3. Add the exit code
System. Web. Security. formsauthentication. signout ();
Response. Redirect ("login. aspx ");

Read the full text

Category:C #/Asp.net view comments

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.