asp.net Internet Security Forms authentication Method _ Practical Tips

Source: Internet
Author: User
Tags anonymous decrypt httpcontext ticket
This article describes how asp.net1.1 and asp.net2.0 are implemented on forms authentication, and what improvements or changes have been made to asp.net2.0 compared to the previous version. I believe that readers have seen many such articles, not on the Internet or some professional books, Recently, the Model & Practice team members released the WCF Security Model Guide, it is obvious that the construction of Web site security is always an outdated topic, the author believes that this article is definitely your favorite reference.

The working principle of asp.net security

Web sites have a common security requirement: specific pages allow only certain members or other authenticated users to browse. Making the most of forms authentication is the best way.
Authentication
From the implementation mechanism, asp.net1.1 is consistent with the asp.net2.0 security model. First configure the Web site for Forms authentication mode, after which the user accesses the site's url,forms The authentication system redirects unauthenticated requests to the specified login page. The user enters the credentials (user name password) and submits the page. If the validator verifies that the user's identity is legitimate, a specific cookie (. NET1.1 does not support no cookie mode) is issued to the client. It represents the user's authentication ticket. In such subsequent requests, the client browser sends the cookie to the server, and if the cookie is valid, the user authenticates and allows access to the original requested resource.
Authorized
If the user's request is validated, but the URL he requested is allowed to be accessed by the user, authorization is used. You can use the application configuration file for a friend. You can also work with code in your program to verify that the user is eligible to access the resource. If authorization fails, asp.net Redirects the user to the login page. If the user is authorized, the user is allowed access to the protected resource.
asp.net1.1 Implementation method
The implementation of asp.net1.1 is very simple, but we still need to write some code, and below we will do it step-by-step. For more information on the application configuration section, refer to the MSDN documentation.
L Configure the application to use Forms authentication to edit the Web.config file
Copy Code code as follows:

<configuration>
<system.web>
<authentication mode= "Forms" >
<forms name= ". Aspxcookieauth "loginurl=" Login.aspx "protection=" All "timeout=" path= "/"/>
</authentication>
<authorization>
<deny users= "?"/> <!-refused to be anonymous-->
</authorization>
......
</system.web>
<location path= "Admin" ><!-Configure authorization to only allow users with admins roles to access files in this directory (*.aspx)-->
<system.web>
<authorization>
<allow roles= "Admins"/><!-although the following is configured to deny all users, the allow priority is higher than deny .-->
<deny users= "*"/><!-deny all users-->
<!-
A user or role must be specifically specified as a deny to deny the user or role permission to the URL. If the above example does not specify the <deny users= "*"/> element, then all authenticated users are allowed access to the requested URL, regardless of the role to which it belongs.
-->
</authorization>
</system.web>
</location>
</configuration>

L Create a login page login.aspx
Page preview is as follows, the code details the source of the project attached to this article.

Create a user identity Principal
The asp.net1.1 security model provides four authorization methods, all four of which use the HttpContext.User object for authentication authorization.
L Authorize using application configuration, only users with the specified role can access the folder and subfolder where web.config resides
<authorization>
<allow roles= "Admins"/>
<deny users= "?" />
</authorization>
L use Principlepermissionattribute to control access to classes and methods, allowing only members of the role to be admins to invoke the method
[System.Security.Permissions.PrincipalPermission (system.security.permissions.securityaction.demand,role=) Admins ")]
public static bool MethodName ()
{
...
}
L Programmatically control access to blocks of code using the Principlepermission class, allowing only the admins members to invoke the code after demand
public static bool MethodName ()
{
System.Security.Permissions.PrincipalPermission perm = new System.Security.Permissions.PrincipalPermission (NULL, " Admins ");
Perm. Demand ();
...
}
L Use the IPrincipal.IsInRole method to allow only the members of the role to run the code in the If, in most cases we use this method to determine whether the user has permissions.
public static bool MethodName ()
{
if (HttpContext.Current.User.IsInRole ("Admins"))
{
Some code
}
}
For the above features, programmers must create HttpContext.User objects in the right place to meet the requirements of the validation model. Developers must write HttpApplication:: AuthenticateRequest event. The occurrence of this event means that the user has been authenticated by forms.
Implement Application_AuthenticateRequest in Global.asax.
protected void Application_AuthenticateRequest (Object sender, EventArgs e)
{
HttpApplication app = (HttpApplication) sender;
HttpCookie cookie = Request.cookies[formsauthentication.formscookiename];
if (cookie!= null)
{
String encryptedticket = cookie. Value;
FormsAuthenticationTicket ticket = Formsauthentication.decrypt (encryptedticket);
Gets the role owned by the user who joined the validation ticket at logon authentication, but not when it is actually developed, and recommends getting that user role information from the database.
Because the cookie itself has a length limit, and it is not safe to store the user role on the client.
If the cookie does not limit size, then its size to a few MB or GB, the client and the server each communication, will be what kind of situation, hehe.
This shows only how to add role information to the user principal GenericPrincipal.
string[] roles = ticket. Userdata.split (new char[] {', '})//Get role
FormsIdentity identity = new formsidentity (ticket);
System.Security.Principal.GenericPrincipal user = new System.Security.Principal.GenericPrincipal (identity, roles);
App. Context.User = User;
App. Context.User = new System.Security.Principal.GenericPrincipal (New System.Web.Security.FormsIdentity ( Formsauthentication.decrypt (cookies. Value)), the new string[]{"Admins"});
}
}
Or the formsauthentication_authenticate effect is the same in Global.asax.
void FormsAuthentication_OnAuthenticate (object sender, Formsauthenticationeventargs e)
{
HttpCookie cookie = Request.cookies[formsauthentication.formscookiename];
if (cookie!= null)
{
String encryptedticket = cookie. Value;
FormsAuthenticationTicket ticket = Formsauthentication.decrypt (encryptedticket);
string[] roles = ticket. Userdata.split (new char[] {', '});
FormsIdentity identity = new formsidentity (ticket);
System.Security.Principal.GenericPrincipal user = new System.Security.Principal.GenericPrincipal (identity, roles);
E.context.user = User;
}
}
In fact, FormsAuthenticationModule will automatically generate a user object, except that the role list for this object is empty, it can only represent authentication, not authorization, because we limit the access role of the directory, so the developer must implement the code above, To meet our needs, if your site only needs to be authenticated, you do not have to implement these methods.
When the user requests the URL, the ASP. NET request channel triggers a sequence of events that complete a series of tasks, including forms authentication events and authorization events. The following is shown:
BeginRequest Request Start Event
AuthenticateRequest validation through events (the above two pieces of code are executed in this event)
Postauthenticaterequest user identity has been established when ASP.net 2.0 introduced the event, which will be mentioned later.
AuthorizeRequest occurs when the security module has authenticated a user authorization
.... other events slightly;
It is these events that contributed to the implementation of the ASP.net framework validation model, and by completing several of the above steps, the site content has been protected by the authorization mechanism.
Let's take a look at how the Asp.ne security model is authorized.
L asp.net 1.1 security model verification Authorization principle
In ASP.net, there are two ways to restrict access to resources: File authorization and URL authorization, and here we only ask the latter.
URL authorization is executed by UrlAuthorizationModule, which maps users and roles to the ASP.net application The URL. This module can be used to selectively allow or deny access to specific users or roles to any part of the application that typically specifies an authorized user or role for the directory in the Web.config file.
The HTTP module is registered in the ASP.NET framework default application configuration file, as follows:

The following is a simple analysis of UrlAuthorizationModule's source code to see how the validation model validates the authorization rules specified in web.config.

UrlAuthorizationModule occurs when the application initializes to the httpapplication::authorizerequest event ( Security Module Authenticated user authorization ) Registers the delegate code, which calls authorizationconfig::isuserallowed inside the code. The screenshot of the method is as follows:

The above code calls the Authorizationconfigrule::isuserallowed method again, the screenshot is as follows:

Because the httpapplication::authorizerequest event was executed after the HttpApplication:: AuthenticateRequest event (see the list of events I mentioned In the AuthenticateRequest event described earlier, we modified the Context.User object and added role information, so the authorizerequest event was found when the user's permissions were validated The Context.User object has everything in it, so it allows the user to access the requested resource, otherwise the request is returned to the specified page . The above is the principle of asp.net1.1, how do you understand ?

asp.net2.0 You can still use such a mechanism, but add new features. Here is how to achieve in the asp.net2.0!

asp.net 2.0 Implementation Mode

asp.net2.0 is implemented in much the same way as the asp.net1.1 implementation , and also supports the previous version of the security model . However, new membership and role management authorization models are added . Here is a brief introduction to asp.net2.0 's new content .

L application Configuration new Properties

<system.web>

<authentication mode= "Forms" >

Defaulturl is a new property of the asp.net2.0 version that is redirected to the URL when the model redirection URL is validated. The default value is "default.aspx".

Although the asp.net1.1 version does not have this attribute, the default in the program is "Default.aspx". Or the asp.net2.0 configuration is more flexible.

<forms loginurl= "logon.aspx" protection= "All" name= ". Aspxformsauth "path="/"Defaulturl=" index.aspx "></forms>

</authentication>

<authorization>

<deny users= "?"/>/* Anonymous user * *

</authorization>

</system.web>

Log on using Membership Authentication

asp.net membership is primarily used for asp.net Forms authentication , in conjunction with ASP. NET2.0 Login controls can implement Forms authentication without having to write any code .

First create the login page login.aspx, the login control into the form, do not write any login event code , compared to the ASP. NET1.1 Save time is not a bit of the slightest .

Use role management for access authorization

Role management can help you manage authorization , enabling you to specify which resources are accessible to users in your application . Role management lets you group users by assigning them to the appropriate roles , making it easier to control access rights .

1. Enable role Management

To enable this feature , modify the web.config file to add child nodes to the <system.web> configuration node as follows :

<rolemanager enabled= "true" cacherolesincookie= "true"/>

The cacheRolesInCookie property represents whether to cache role information so that you do not have to get the role from the database each time to improve the performance of your application .

But putting a character in a Cookie is always risky , it can be tampered with , and then use it to access an unauthorized resource .

However, you can use the Deletecookie method of the role API to remove the cache Cookie each time a user logs on, which makes the risk smaller.

Recommended code :

if (Membership.ValidateUser (username, password)) {

Roles.deletecookie ();

FormsAuthentication.RedirectFromLoginPage (username, false);

}

Special note : when role management is available in the application configuration and the provider program is aspnetsqlprovider , sqlroleprovider the GetRolesForUser method calls the private static method of the System.Web.DataAccess.SqlConnectionHelper class Ensuresqlexpressdbfile creates an empty aspnetdb.mdf Local database that contains information such as membership and role management , required table structure, and so on .

2. Configuring members and Roles

Using VS2008 's own Configuration tool to set members and roles is the easiest , click the [item] in the menu bar, the last item in the drop-down menu [asp.net configuration ], set the member and role relationships in the pop-up form . The following figure shows :

There are content to manage users and roles within the Security tab, as shown in the following figure:

This example creates a user "Iori" with a role "Admins" and specifies that the user is a member of the Admins role.

The tool also automatically creates a local database ( if it is not yet created). The configuration associated with it is specified in the Machine.config file, as shown in the following illustration, You can change the file name of the database by default to "Aspnetdb.mdf".

Well , by completing a few steps above , the site content has been protected by the authorization mechanism , you can use just add users to try to log in.

Compared to the previous version, asp.net2.0 saves developers a lot of time in forms authentication, and it's a lot easier to do without developers writing any code, so let's explore .

L asp.net 2.0 security Model Verify the principle of authorization

1. Verification Principle

In . net1.1 The developer must write a logon event for the login page to Verify that the user entered a username and password that is valid and asp.net 2.0 The membership provider and the standard login server control are introduced implicitly using Forms authentication, and the login control contains the program logic to authenticate the user name. This means that the login control automatically matches the user's entered user name and password with the user in the membership database , and writes a specific Cookie to the client if a successful match occurs .

2. Principle of Authorization

Or take UrlAuthorizationModule to say, If you do not enable role management, the implementation is similar to asp.net1.1, but because asp.net2.0 joined the role management model, The role management model uses two classes: RolePrincipal and rolemanagermodule to implement role authorization . if the application-configured role management is available, these two new objects will be applied to the lifecycle of the ASPX page, as RoleManagerModule is initialized to the HttpApplication object to load the delegate code, which will postauthenticaterequest the app. The Context.User object is wrapped as a RolePrincipal object.

The Postauthenticaterequest event was added to the ASP.net 2.0 , which occurred after the authenticaterequest event . The user identity has been established on behalf of the security module, so the RolePrincipal object is regenerated using the user identity in this event .

The following is an excerpt from the delegate code.

.../ omit several code

HttpApplication application = (HttpApplication) source;

HttpContext context = Application. context;

if (This._eventhandler!= null)

{

Rolemanagereventargs e = new Rolemanagereventargs (context);

This._eventhandler (this, e);

if (e.rolespopulated)

{

to determine whether the developer wrote an event handler in Global.asax , the code shown below .

/*

// here shows how to Customize roles in Global.asax

void Rolemanager_getroles (object sender, Rolemanagereventargs e)

{

if (e.context.request.isauthenticated)

{

E.context.user = new GenericPrincipal (new genericidentity (e.context.user.identity.name), new string[] { "Admins"});

e.rolespopulated = true;

}

}

*/

if e.rolespopulated is true , create role information on behalf of the developers themselves ,

RoleManagerModule will not generate the RolePrincipal object .

Return

}

}

......

if (!) ( Context. User is RolePrincipal))

{

Context. User = new RolePrincipal (context. User.Identity);

}

Thread.CurrentPrincipal = context. User;

Note : We do not generate the User object in the AuthenticateRequest event, as in asp.net1.1 . However , the user object uses the particular Cookie of Forms authentication in the FormsAuthenticationModule HTTP module Is repackaged as a GenericPrincipal object ( the role is empty ).

Before you can explain what the RolePrincipal object is used for, you need to know when the object is being used.

The  event authorizerequest registered with the HttpApplication object when the UrlAuthorizationModule is initialized is triggered.  
In this event, the method IsInRole the RolePrincipal object (that is , Context.User) is invoked , and the IsInRole method automatically finds the role provider (this example uses the default provider  AspNetSqlProvider, the database is a previously auto-generated aspnetdb.mdf) and validates the user role, the code screenshot reads as follows:      

And the Isuserallowed method will eventually call the RolePrincipal diagonal IsInRole method to determine whether the current user has a role , the method screenshot as follows :

These are the principles and implementations of forms authentication implemented by ASP.NET2.0 membership and role management , Although the default membership and role database fields generally do not meet the needs of specific projects. Fortunately, the ASP.net 2.0 provides an extensible arch-lifting program model that enables developers to customize membership providers and role management models.

Conclusion

the authentication and authorization method for Web site applications is a challenging task, and forms authentication provides an important security advantage in Web site construction by providing user profiles and support for roles. Simplifies the work that programmers usually need to write a lot of code to do. If the reader has any questions or have different views on the above description, please contact me to communicate with each other!

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.