How to use form forms authentication

Source: Internet
Author: User
Tags anonymous auth datetime parent directory require ticket

Http://blog.csdn.net/iceblue2005gather/archive/2006/04/28/695006.aspx

ASP. NET security authentication, a total of "Windows" "Form" "Passport" "None" four authentication modes. "Windows" and "none" do not play a protective role, not recommended; "Passport" I have not used, alas ... So I had to talk about "Form" certification. I intend to divide it into three parts:

The first part--how to achieve from certification;

The second part of the--form certification of practical use;

The third part--Realization of single Login

How to use Form form authentication in the first part

First, create a new test project

In order to better illustrate, it is necessary to create a new test project (for the moment "formtest" bar), contains three pages enough (Default.aspx, Login.aspx, userinfo.aspx). What. Someone will not create a new project, and will not add pages. You ask me what to do. I think this is done: drag out, play back the original, learn from kindergarten ...

Ii. modifying the Web. config

1. Double-click the Web. config in the project (no, can't find the PP)

2. Find the following text <authentication mode= "Windows"/> Change it to:

<authentication mode= "Forms" >

<forms loginurl= "Login.aspx" name= ". Aspxauth "></forms>

</authentication>

3, find <authorization> <allow users= "*"/></authorization> replaced

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

There's nothing to say here, just copy the past. Nevertheless, there are those who are mistaken, as follows:

<authentication mode= "Forms" >

<forms loginurl= "Login.aspx" name= ". APSX "></forms>

<deny users= "?" ></deny>

</authentication>

To ask who put <deny users= "?" ></deny> put <authentication> in, I would be honored to tell you that it was N years ago I:<authentication> and <authorization> are all based on Auth the beginning of the letter is the end of the ation, how similar; I think they are a gang of words.

Third, write. cs code--Login and exit

1. Login Code:

A, the book introduced

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've been looking for N long to find

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");

}
}

Both of the above can be issued after the verification of the Cookie, that is, by authentication, the difference:

Method a) refers to the verification and return to the request page, commonly known as "where to hit where to go." For example: The user does not log in before directly in the IE address bar input http://localhost/FormTest/UserInfo.aspx, then the user will see is login.aspx? Returnurl=userinfo.aspx, enter the user name and password after the successful login, the system will be based on the value of "RETURNURL" to return to the corresponding page

Method B) is a two-step walk: Through the verification of the direct issuance of cookies, the jump page will be the programmer's own designation, this method is used to default.aspx the use of the framework structure of the system.

2. Exit Code:

private void Btn_logout_click (object sender, System.EventArgs e)
{

System.Web.Security.FormsAuthentication.SignOut ();

}

Iv. How to judge the verification or not and obtain the user information after verification

Sometimes, on the same page, you need to tell if the user is logged in and then render a different layout. Some people like to use the Session to judge, I do not oppose such practices, here I just want to tell you there is another way, and look at the following code:

if (User.Identity.IsAuthenticated)
{

You have passed the verification and know what to do.

}

User.Identity also has two properties AuthenticationType (authentication type) and name (user name), you should be aware of the Name property, Here the User.Identity.Name will get, validate through (RedirectFromLoginPage or SetAuthCookie) when we bring in the first parameter of this. Txt_username.text. This parameter is very important, related to various ... All sorts of circumstances, what the remark, and listen to tell ...
Flexible use of deny and allow in form forms authentication and protection. htm and other files

The second part of the actual application of Form certification

Scope of Web. config

When you create a new project, vs.net establishes a fixed-content Web. config in the project root directory. In addition to the project root, you can also create a Web. config in either directory, provided that the application-level nodes appear only in the root directory of Web. config. As to which is the application level node, this question, actually I also not very clear, hehe. Computer is not my invention, Microsoft is not my creation, C # is not my decision, the immortal also has not known, so I do not know is normal. That being said, as long as it does not error, it is right.

For the scope of the Web. config setting, keep the following two points in mind:

1. The settings of the Web. config will be used for all the files in the directory and their subdirectories (inheritance: Child with parent surname)

2. Web. config settings under subdirectories overwrite settings inherited by parent directory (overwrite: Magistrate is better than present tube)

Ask a question: Is there a configuration file that is larger than the scope of the root directory. config. The third part of the book will be known.

Vi. learning to refuse and skillfully use permission

Back to our first round of the new test project "Formtest", since to verify, according to international practice, you have to have a user name and password. Then, these users are the administrator himself in the database to build, or user registration, Administrator audit well. As long as not a general idiot, all know to choose the latter. You also don't say, my company also really has individual project is the Administrator connect to the database to build account, belong to the more special fool, we don't learn him or not, or honestly add two pages--registration page (register.aspx) and Audit page (auditing.aspx).

The problem will finally come to the surface, when you do a good register.aspx, when you want to visit it suddenly feel wrong, how to return to the login page. You look closely at the URL, is not become: Login.aspx? Returnurl=register.aspx. How to do, the user is because there is no account to visit the registration page AH. (This sentence is purely nonsense, there are accounts who have run to register.) I often say to my colleagues: "The way is people want to come out." ”

1, create a new directory public, for storing some common files, such as perpetual calendar, script ah ...

2. In Solution Explorer, right-click on directory public to add a Web. config

3. Remove the contents of the above Web. config, leaving only the following:

<?xml version= "1.0" encoding= "Utf-8"?>

<configuration>

<system.web>

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

</system.web>

</configuration>

Finally cut to the chase, not easy. Based on the "overwrite" principle, we know that the above Web. config will override the <authorization> node settings in the root directory, Web. config:

<allow users= "*"/> replace <deny users= "?" ></deny>

Note: The meaning of "allow" is allowed; "*" means all users;

"Deny" means to refuse; Represents an anonymous user;

Therefore, files that are in the public directory allow everyone to browse, including unauthenticated users. Drag the register.aspx in, and no one will ever 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 the administrator or supervisor, and do not want others to browse this page (the truth is often in the hands of a few people, this is not a thing), how to do. "The way is people want to come out" hehe ... Create a new directory for the Administrator Managesys, and a new web. config is added to this directory. The contents are 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); by verifying, issuing cookies

As I have emphasized before, it is important to note that the first parameter is important and to what extent. Speaking of which, I am afraid the earth people know-it is the basis for allow and deny. If the user fills in the "Admin" that is this. Txt_username.text = "Admin"; Then enter the system, he will be able to access the Managesys directory of the page, and other unauthorized people will be rejected.

Above from
Http://www.rjjd.com/bbs/simple/index.php?t17819.html

1: In Web. config, add form authentication;

<authentication mode= "Forms" >
<forms name= "auth" loginurl= "index.aspx" timeout= "></forms>"
</authentication>
<authorization>
<deny users= "?"/>
</authorization>
2: If there is a registration page should also allow anonymous users to call the registration page to register;
The following code should be between <configuration><system.web>, and should not be included in the <SYSTEM.WEB> Between </system.web>;
----------------means that anonymous users are allowed access to the Userreg.aspx page.
<location path= "Userreg.aspx" >
<system.web>
<authorization>
<allow users= "?"/>
</authorization>
</system.web>
</location>
3 after the successful login to create an authentication ticket, indicating that the legitimate user has passed the certification;

if (login successful)

System.Web.Security.FormsAuthentication.SetAuthCookie (user name, false);

1. Use forms validation to store user-defined information

The internal mechanism of forms validation is to encrypt the user data after it is stored in a cookie-based ticket formsauthenticationticket, because it is specially encrypted, so it should be more secure. and. NET in addition to use this note to store their own information, but also left a place for users to free control, this is now to say the UserData.

UserData can be used to store string types of information, and also enjoy the encryption protection provided by forms validation, when we need this information can also be obtained through a simple get method, both security and ease of use, to save some of the necessary sensitive information is still very useful.

Let's look at how to use UserData, and then give an example of what is actually used.

Create a new ticket to ticket the client IP into the UserData
FormsAuthenticationTicket ticket=new FormsAuthenticationTicket (
1,username.text,datetime.now,datetime.now.addminutes (30),
false,request.userhostaddress);
Encrypt a ticket
String Authticket=formsauthentication.encrypt (ticket);
Save the encrypted ticket as a cookie
HttpCookie coo=new HttpCookie (formsauthentication.formscookiename,authticket);
Use a new cookie that has been added to UserData
Response.Cookies.Add (COO);

The following is a method signature of one of the overloads of the FormsAuthenticationTicket constructor
Public FormsAuthenticationTicket (
int version,
String name,
DateTime IssueDate,
DateTime expiration,
BOOL Ispersistent,
String UserData
);

Parameters
Version
The version number.
Name
The user name associated with the authentication ticket.
IssueDate
The time the Cookie was issued.
Expiration
The expiration date of the Cookie.
Ispersistent
True if the Cookie is persistent, otherwise false.
UserData
User-defined data that will be stored in a Cookie

Using UserData is also very simple, FormsIdentity's Ticket property provides access to the current ticket, which can be accessed with the UserData attribute after the ticket has been obtained, and is, of course, decrypted.
((System.Web.Security.FormsIdentity) this. Context.User.Identity). Ticket.userdata


The following is a specific application.

Because forms validation is done through cookies, it needs to pass a ticket to work. Although the bill is encrypted, the contents are not visible, but this does not prevent others from using a fake identity to use the ticket (as we can take someone else's key to open someone else's lock), it is more common that the different IP users intercepted the ticket in an unsecured channel, and then use it to carry out some activities outside the security range.

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

But if you can't use SSL. We can judge whether the IP and the ticket match, if the IP is the first to generate the ticket IP, then there is no problem, otherwise destroy the ticket.

To do this, we need to save the user's IP at the beginning of processing the login, so that the IP of the subsequent request can be verified at any time in a subsequent request to be the same as the initial IP. The best place to save this sensitive IP is, of course, UserData, and the time to validate is when the AuthenticateRequest event occurs, the application_ that is defined in Global.aspx.cs to handle this event The AuthenticateRequest method.

The above example has actually saved the user IP to UserData, and the following is the verification process.

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 ticket is invalidated by giving GenericPrincipal empty genericidentity and roles, which forces the user to log in again. To test this method, you can change the condition to equal and see how it works:)

This method also has shortcomings, specifically:

1. Users who use the same agent will have the same IP, so there is no way to protect against such counterfeit attacks.

2. If the user uses dynamic IP, it may cause normal users to be forcibly destroyed by us. In general, however, this approach is more feasible.


2. Use security features with forms validation for safe operation.

PrincipalPermissionAttribute can be used with forms authentication for role-based or user-specific security validation, which is not available at the assembly level. Its scope can be a class or a specific method. 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!");
}

#region the code generated by the Web Forms Designer
Override protected void OnInit (EventArgs e)
{
//
CODEGEN: This call is required for the ASP. NET Web Forms Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

<summary>
The designer supports the required method-do not use the Code editor to modify
The contents of this method.
</summary>
private void InitializeComponent ()
{
This. Load + = new System.EventHandler (this. Page_Load);
}
#endregion

}


Note that this example starts with the entire class, executes after the build, and if the current user is not Notus, an exception System.Security.SecurityException will occur, prompting the request for principal permission to fail. Conversely, it can be accessed smoothly, and output two Hello world!, note is two. The security scope is now the entire class.

Next we change the scope of the feature. Move the attribute declaration to the SayHello2 method, and then run it again, and you will see that the program throws a System.Security.SecurityException after running to the SayHello2 method. This means that the security scope is now reduced to the method level.

This feature enables user-and role-based security protection by setting users and roles. In addition, the first parameter it uses is the SecurityAction enumeration, which sets a specific level of protection or measure. As we are now using this demand, it is required that all advanced callers in the call stack have been granted the permissions specified by the current permission object.

The following is an example of MSDN

Example

The following example shows how you can use PrincipalPermission declaratively to require that the current user be Bob and belong to the Supervisor role.
[PrincipalPermissionAttribute (SecurityAction.Demand, name= "Bob",
Role= "Supervisor")] The following example shows how to require the current user's identity to be Bob, regardless of the role membership condition.
[PrincipalPermissionAttribute (SecurityAction.Demand, name= "Bob")]
The following example shows how to require only the user to be authenticated.
[PrincipalPermissionAttribute (SecurityAction.Demand, Authenticated=true)]

Again, the user and role in this can be integrated with the forms validation, whereby we can use PrincipalPermissionAttribute in some important classes or methods to arm our own program to the home.

In fact, this feature is much more than that, and more detailed information can be consulted

Or:
1. Configuring the Web. config file

Set to form authentication:
<authentication mode= "Forms" >
<forms name= "oursnet" loginurl= "Login.aspx" timeout= "/>"
</authentication>
which
Name: The cookie used to determine when the user is authenticated
Loginurl: The page is redirected when the user is not logged in
Timeout: Time-out, in minutes

Anonymous Logon is not allowed
<authorization>
<!--allow all users-
<deny users= "?"/>
<!--<allow users= "[comma-delimited list of users]"
roles= "[comma-delimited list of roles]"/>
<deny users= "[comma-delimited list of users]"
roles= "[comma-delimited list of roles]"/>
-
</authorization>
which
Users: Represents a list of people who are forbidden to access the resource, using the wildcard character "?" Denying anonymous user access, using "*", means denying all user access.

2. Add the code for login success:

session.contents["UserName"]=txtuser.text;
FormsAuthentication.RedirectFromLoginPage (Txtuser.text,false);
Response.Redirect ("index.aspx");

3. Add code when exiting
System.Web.Security.FormsAuthentication.SignOut ();
Response.Redirect ("Login.aspx");

Configuring the Web. config file

Set to form authentication:
<authentication mode= "Forms" >
<forms name= "oursnet" loginurl= "Login.aspx" timeout= "/>"
</authentication>
which
Name: The cookie used to determine when the user is authenticated
Loginurl: The page is redirected when the user is not logged in
Timeout: Time-out, in minutes

Anonymous Logon is not allowed
<authorization>
<!--allow all users-
<deny users= "?"/>
<!--<allow users= "[comma-delimited list of users]"
roles= "[comma-delimited list of roles]"/>
<deny users= "[comma-delimited list of users]"
roles= "[comma-delimited list of roles]"/>
-
</authorization>
which
Users: Represents a list of people who are forbidden to access the resource, using the wildcard character "?" Denying anonymous user access, using "*", means denying all user access.

2. Add the code for login success:

session.contents["UserName"]=txtuser.text;
FormsAuthentication.RedirectFromLoginPage (Txtuser.text,false);
Response.Redirect ("index.aspx");

3. Add code when exiting
System.Web.Security.FormsAuthentication.SignOut ();
Response.Redirect ("Login.aspx");



trackback:http://tb.blog.csdn.net/trackback.aspx?postid=695006

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.