Secure applications in ASP.net 2.0

Source: Internet
Author: User
Tags anonymous exit config constructor httpcontext iis include valid
Asp.net| Security | procedure

Members and Role manager providers--now ASP.net 2.0 contains built-in member and role management services. Since these services are provider-driven (Provider-driven), you can easily change it, or replace it with a custom implementation.

Login Controls--The new login control provides the basic module for a site's authentication and authorization UI, such as a login form, creating a user form, password retrieval, a custom UI for logged-in users, or roles. These controls interoperate with the user and role information defined by the site using the built-in member and role services in ASP.net 2.0.

An important part of most Web applications is to identify users and control access to resources. The operation of detecting the requested entity (entity) identity is authentication (authentication). Typically, for authentication purposes, the user must provide credentials such as account number/password. Once the authenticated identity is valid, it is necessary to detect whether the identity has access to the specified resource, which is the authorization (authorization). Asp. NET, together with IIS, provides authentication and authorization services for your applications.

An important feature of COM objects is that it can control the identity of those running COM object code. When a COM object runs code with the requested entity, it is called impersonation (impersonation). Asp. NET Framework component applications can choose to mimic requests.

Some applications also want to dynamically customize content based on the identity of the request or the role that the requested identity belongs to. Asp. NET Framework component applications can dynamically detect whether the identity of the current request belongs to a role. For example, an application might want to detect whether the current user belongs to the Administrator role to conditionally generate content for an administrator.

ASP.net 2.0 's membership features make it easier for you to create and manage users. Member attributes typically work with another new feature called the Role Manager. The Role Manager provides a low-level structure for creating roles and assigning users to roles. When members, Role Manager features, and form authentication work together, ASP.net 2.0 can provide end-to-end support for creating, authenticating, and authorizing users.

Both members and role managers are designed with a provider based model. The provider extracts physical data stores of attributes from classes and business logic exposed by the attribute. The member and Role Manager attributes are all provided with the Microsoft SQL Server provider. The member attribute also comes with a provider that processes the Active Directory and Active Directory Application Mode (ADAM). The Role Manager feature comes with a provider that leverages Windows Server 2003 licensing management features. You can create a custom provider and configure it to work with the members and role manager attributes. When you use a custom provider, pages that take advantage of the members and Role manager features will continue to work without change.

A login control is a set of custom server controls that provide a common user interface for authentication and authorization transactions. Login controls take advantage of the functionality in the members, Role Manager, and form authentication features.

   Certification and Authorization

Asp. NET supports the use of basic, Digest, and Windows authentication together with IIS. Asp. NET supports the Microsoft Passport Authentication Service, which supports the single sign-on service and the User Configuration service. Asp. NET also supports a powerful service that uses forms-based authentication. forms-based authentication uses cookies to authenticate users and allows the application to perform its own credential verification process.
We want to realize that ASP. NET authentication service is restricted by the authentication service provided by IIS. For example, to use Basic authentication in an IIS application, you must use the Internet Services Administration tool to configure your application to use Basic authentication.

Asp. NET provides two types of licensing services:

· Check ACLs (access control lists) or resource permissions to see if an authenticated user has access to the resource.

· URL authorization, which authorizes an identity to use a certain web space.

To illustrate their differences, let's look at an example of an application that allows anonymous users to use Iusr_mymachine account access. When a request for a ASP.net page (such as "/default.aspx") is authenticated, it is checked against the ACL of the file (for example, "c:\inetpub\wwwroot\default.aspx") to see IUSR_ MyMachine account has permission to read this file. If you have permission, you authorize access. If the Web content is on an NTFS volume and the virtual directory is configured to use Windows authentication, the authorization for the file is automatically executed.

For URL authorization, the check is based on the configuration data for the ASP.net application. If you allow access to the requested URL, the request is granted. In the example, ASP. NET checks whether anonymous users have access to/default.aspx (that is, the check process is based on the URL itself, without the final resolution of the file based on the URL).

This difference may seem subtle, but it allows applications to use similar forms-based authentication or Passport authentication in which users do not need to correspond to a computer or domain account. It also allows you to authorize virtual resources (there are no physical files below the resources). For example, an application can map all requests to. stk files to a handler that quotes the securities based on the variables in the query string. In this case, there is no physical. stk file available for ACL checking, so use URL authorization to control access to virtual resources.

File authorization usually relies on the authenticated account provided by IIS for execution. If anonymous access is allowed, it is the configured anonymous account. Otherwise, is NT account. It works the same way as an ASP.

You can set the ACL (Access control list) for a file or directory on the Security tab of the Resource Manager Properties page. URL authorization is configured as part of the ASP.net framework component application and is fully explained in the "authorized Users and Roles" section.

In order to activate the ASP.net authentication service, you must configure the <authentication> element in the application's configuration file. This element can contain any of the values listed in the following table.

Value Describe
None There is no active asp.net authentication service. Please note that the IIS Authentication Service still exists.
Windows Asp. NET Authentication Service attaches a WindowsPrincipal (System.Security.Principal.WindowsPrincipal) to the current request to ensure authorization based on NT users or groups.
Forms Asp. NET authentication Service manages cookies and redirects unauthorized users to the login page. It is usually used when IIS allows anonymous access to the application.
Passport Asp. NET Authentication Service provides a convenient package for the Passport SDK (you must install).

For example, the following configuration file allows an application to use forms-based (cookie) based authentication:

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

   using the Login control

The following example shows how to use a login control in an application.

   creating and logging on to users

In the example we will see the homepage of the site, which contains a LoginStatus control that prompts the user to log on to the site. The LoginStatus control on this page checks whether the user is currently authenticated and displays a login link to the user. The user clicks on this link to see the default Login.aspx page, which has been configured as form authentication in Web.config. The login control is displayed on the Login.aspx page (note that the VisibleWhenLoggedIn property of the login control is ignored on the default login page). In the example, the login control sets an additional attribute, displays the "Create User" link, and clicking the link accesses another page that uses the CreateUserWizard control. By default, the CreateUserWizard control contains two steps, in the first step, the user enters the necessary information, and when they click the "Create User" button, the control passes the information to the member API. If the member API cannot establish the user, the appropriate error message is displayed in the control, and the control loads into the second step of the wizard if the user is created successfully. In the example, the Continuedestinationpageurl property is set to return to the home page after the user is created successfully. By default, when a user is successfully created, CreateUserWizard authenticates and logs on to the user. When the user returns to the home page, they will notice that the LoginStatus is removed, that they have passed the authentication, and that a logout link is displayed. Clicking on the login link will cause the user authentication ticket (ticket) to be cleared and display the login link. At this point, users can click on the login link, because they have created a user account, so you can enter a username and password on the login.aspx to login to the site. You may notice that the login control displays a "Remember account (remember me)" check box. When this box is checked and successfully logged on, a cookie is written to the user's computer, which defaults to a 50-year duration. You can disable this option by setting the login control's Displayrememberme and Remembermeset properties to false. To see the code for the sample, you can see that the transaction does not have any code, and only a few properties are set. The style properties of these controls are set by the style sheet that the site applies to.

Login.aspx
<%@ Page language= "VB" masterpagefile= "~/site.master"%>
<asp:content id= "Content1" contentplaceholderid= "mainbody" runat= "Server"
<asp:login id= "Login1" runat= "Server" createuserurl= "createuser.aspx" createusertext= "Create a New account"/>
</asp:Content>

Createuser.aspx
<%@ Page language= "VB" masterpagefile= "~/site.master"%>
<asp:content id= "Content1" contentplaceholderid= "mainbody" runat= "Server"
<asp:createuserwizard id= "CreateUserWizard1" runat= "Server" continuedestinationpageurl= "home.aspx"/><BR/>
<a Href= "Home.aspx" >return to Default home Page </a> <BR/>
<a Href= "Homeloginview.aspx" >return to LoginView home Page </a> <BR/>
<a Href= "Homechangepassword.aspx" >return to ChangePassword home Page </a> <BR/>
</asp:Content>
   displaying different content to authenticated users

The following example demonstrates the use of the LoginView control to display different content for authenticated users and anonymous users. Although nothing is shown in the example, the LoginView control supports displaying different content based on user roles. The anonymoustemplate template in the LoginView control contains a login control, and the LoggedInTemplate template contains the LoginName control. The LoginName control uses the formatted string property to display the welcome and user names. Please use the account created in the previous example or recreate an account to login to the site and click on the logout link at the top of the page.

<%@ Page language= "VB" masterpagefile= "~/site.master"%>

<asp:content id= "Content1" contentplaceholderid= "mainbody" runat= "Server"
<asp:loginview id= "LoginView1" runat= "Server"
<loggedintemplate>
<h1>
<asp:loginname id= "LoginName1" runat= "Server" formatstring= "Welcome {0}"/>
</h1>
</loggedintemplate>
<anonymoustemplate>
<asp:login id= "Login1" runat= "Server" createuserurl= "createuser.aspx" createusertext= "Create a New account"/>
</anonymoustemplate>
</asp:LoginView>
</asp:Content>
   Modify Password

By default, the ChangePassword control requires the user to pass the site's authentication to change their password. However, in the following example, we set the Displayusername property to True, and the result is that the user can be authenticated by the ChangePassword control before changing his or her password, or by a site-authenticated user entering a different account to change the password. Examples are also linked to creating a user page that allows you to create a valid user and test the sample.

<%@ Page language= "VB" masterpagefile= "~/site.master"%>
<asp:content id= "Content1" contentplaceholderid= "mainbody" runat= "Server"
<asp:changepassword id= "ChangePassword1" runat= "Server" createuserurl= "createuser.aspx" Create a New Account "Canceldestinationpageurl=" homechangepassword.aspx "Displayusername=" true "continuedestinationpageurl=" Homechangepassword.aspx "/>
</asp:Content>

using the members and Role manager APIs

   Members

Member attributes are built around two core classes: Membership and MembershipUser. The Membership class provides methods for creating users (MembershipUser class processing), as well as common methods for managing users. Users established with the membership class are authenticated by the ASP.net application.

Common transactions performed by the Membership class include:

· Create a new MembershipUser

· Validates the username-password combination when the user attempts to log on. Next you can use form authentication to generate a cookie indicating that the user is logged on to the site.

· Retrieving MembershipUser instances

· Update MembershipUser Instance

· Search for users based on different criteria

· Get the authenticated user at the current online

· Remove a user from the system when it is not needed

Once you have acquired the MembershipUser instance, you can use the MembershipUser class directly to perform the following transaction:

· Accessing the properties of the MembershipUser class in the application

· Retrieves the user's password (can only be used if the member attribute is configured to allow password retrieval)

· Change or reset a user's password

· Change user password questions and answers (if member attributes are configured to prompt user password questions and answers before retrieving or updating a password)

· Unlock users who are locked out because of a bad password or password answer

   Role Manager

The core class of the role manager is the roles class. Roles provides a way to create roles and assign users to roles. It also provides a way to manage role information.

Common transactions that can be performed using the roles class include:

· Create a new role

· Delete an existing role

· Assigning users to roles

· Remove a user from a role

· Detects whether a user is authorized for a particular role

· Search for users in a specific role, retrieving all users in the role

· Get role information for a specific user

The Role Manager feature also contains HttpModule. This module is responsible for retrieving the roles assigned by the user and storing the information in RolePrincipal, which exists in the HttpContext of the page. The presence of RolePrincipal in HttpContext enables you to use <authorization> elements to protect pages and directories. Depending on the role information stored in RolePrincipal, users can only gain access to specific pages and directories within the site.

   Sample

The following example shows how to use the member APIs in an application.

   Create a new user

The following example shows how to create a new membershipuser. The example uses the Membership.CreateUser overload, which returns a status parameter. Other overloads can also be used, and they throw exceptions rather than return status codes. Note that by default, the member attribute requires a password of at least 7 characters in length, and the password contains at least one non-numeric character.

<script runat= "Server" >
Sub Btncreate_click (ByVal sender as Object, ByVal e as System.EventArgs)
Dim userName as String = Txtuserid.text
' This value is encrypted or hashed and does not show
Dim password as String = txtPassword.Text
Dim Email as String = Txtemail.text
Dim passwordquestion as String = Ddlpasswordquestion.selectedvalue
' This value is encrypted or hashed and does not show
Dim passwordanswer as String = Txtpasswordanswer.text
Dim result as MembershipCreateStatus

Membership.CreateUser (userName, password, email, passwordquestion, passwordanswer, True, result)

Lblresults.visible = True
Select Case Result
Case Membershipcreatestatus.success
Txtuserid.text = Nothing
txtPassword.Text = Nothing
Txtemail.text = Nothing
Ddlpasswordquestion.selectedindex =-1
Txtpasswordanswer.text = Nothing
Lblresults.text = "User successfully created!"
Case Membershipcreatestatus.invalidusername
Lblresults.text = "The username format was invalid. Please enter a different username. "
Case Membershipcreatestatus.invalidpassword
Lblresults.text = "The password was invalid:a password cannot is an empty string and must also meet the Pasword Requirements of the configured provider. Please enter a new password. "
Case Membershipcreatestatus.invalidemail
Lblresults.text = "The email format was invalid. Please enter a different username. "
Case Membershipcreatestatus.invalidquestion
Lblresults.text = "The password question format was invalid. Please enter a different question. "
Case Membershipcreatestatus.invalidanswer
Lblresults.text = "The password answer format was invalid. Please enter a different answer. "
Case Membershipcreatestatus.duplicateusername
Lblresults.text = "The username is already in use. Please enter a new username. "
Case Membershipcreatestatus.duplicateemail
Lblresults.text = "The email address are already in use. Please enter a different e-mail address. "
Case Else
Lblresults.text = "An error occurred while creating the user."
End Select
End Sub
</script>
   User Login and Access user Properties

The following example shows the user logging in using the Membership.ValidateUser method. It also demonstrates how to use form authentication and member attributes at the same time when you log on to a user. After creating the user in the example above, enter the voucher on the login page. Once you have logged in, you will be redirected to a page that uses Membership.getuser to retrieve MembershipUser instances corresponding to the logged-in user. Also note that this page also shows the user properties set on the directory, which can only be accessed by authenticated users. Click on the logout link at the bottom of the page to exit the site.

<script runat= "Server" >
Protected Memuser as MembershipUser

Sub Page_Load (ByVal sender as Object, ByVal e as System.EventArgs)
Memuser = Membership.getuser ()
End Sub

Sub Linklogout_click (ByVal sender as Object, ByVal e as System.EventArgs)
FormsAuthentication.SignOut ()
Roles.deletecookie ()
Formsauthentication.redirecttologinpage ()
End Sub
</script>

User name/id: <% = Server.HTMLEncode (memuser.username)%>
email:<% = Server.HTMLEncode (memuser.email)%>
   Update User Properties

Please login with the user credentials established earlier. The page displays the user properties with the new DetailsView control in ASP.net 2.0. The DetailsView control communicates with a data source control. In the example, the ObjectDataSource control retrieves the contents of the MembershipUser instance. You can click the "edit" link at the bottom of the page to get DetailsView into edit mode. MembershipUser e-mail and comments can be modified. Click the "Update" link to save the new value to the database. Note that the page implements the ItemUpdating event in code, and the event is raised by ObjectDataSource. This is necessary, and the MembershipUser class does not have a parameterized constructor, which requires bidirectional data binding using ObjectDataSource. Click on the logout link to exit.

Sub detailsview1_itemupdating (ByVal sender as Object, ByVal e as DetailsViewUpdateEventArgs)
' The update operation must be handled manually because MembershipUser does not have a parameterized constructor
Dim Memuser as MembershipUser = Membership.getuser ()

Memuser.email = CStr (e.newvalues (0))
Memuser.comment = CStr (e.newvalues (1))

Try
Membership.updateuser (Memuser)
E.cancel = True
Detailsview1.changemode (detailsviewmode.readonly)
Catch ex as Exception
Response.Write ("<div> the following error Occurred:<font color= ' red '" + ex. Message + "</font> </div>")
E.cancel = True
End Try
End Sub

   Account lockout

The membership feature automatically tracks the number of times a user retries a password. It also tracks the number of password retries when retrieving a password or resetting a password. The following example shows the automatic account lockout capability and how to cancel the account lockout. First create a new account using the previous "Create new user" example. Next, click the button below to run the "account Logout" example. The login page shows the number of failed attempts to lock the account to be retried. On the login page, use the first account you created and enter the wrong password. Note that after the number of failed retries, if you use the correct password, you cannot log on-this is because the Membership feature automatically locks the account number after a certain amount of failed retries. To unlock the account, please log in with the second account you established. The displayed page is similar to the previous example of displaying user properties. However, this page allows you to enter any user name at the bottom of the page. Please enter the locked account and return. The DetailsView control refreshes and displays the user's information. Note that the check box that identifies the lock state is islockedout selected. Lastlockoutdate has also been updated to show the date when the user was locked out. Click the "Unlock" button at the bottom of the page to unlock the currently displayed user. It calls the Unlockuser method of the MembershipUser instance and unlocks the user. After the user's lock is unlocked, the Islockedout check box is cleared and the Lastlockoutdate property is reset. Click on the logout link at the bottom of the page. Now try to log in with the first account. You can now log in again successfully.

Sub Btnunlockuser_click (ByVal sender as Object, ByVal e as System.EventArgs)
Dim Memuser as MembershipUser = Membership.getuser (txtUsername.Text)
If (not Memuser are nothing and Memuser.islockedout = True)
Memuser.unlockuser ()
End If

' Refresh the selected user's information
Detailsview1.databind ()
End Sub
   Delete User

You can use the Membership.deleteuser method to delete a user. The following example shows how to use form authentication to delete the currently logged-on user and let the user log out.

<script runat= "Server" >
Sub Btndeletecurrentuser_click (ByVal sender as Object, ByVal e as System.EventArgs)
If (Membership.deleteuser (User.Identity.Name)) Then
FormsAuthentication.SignOut ()
Roles.deletecookie ()
Response.Redirect ("~/creatingusers.aspx")
Else
Lblresult.visible = True
Lblresult.text = "The membership user is not deleted."
End If
End Sub
</script>

   managing Roles

The following example shows how an authenticated user can use the Role Manager attribute. All of the sample pages deny anonymous users access. By default, ASP. The Role Manager attribute is not activated in net. However, the use of the web.config in the following example explicitly activates the role Manager attribute.

   Add and remove roles

The following example shows how to use the Roles.createrole and Roles.deleterole methods to create and delete roles. After you create a role or delete an existing role, the page uses the Roles.getallroles method to display all the available roles in the system. The Roles.getallroles return value can be easily bound to any control that supports data binding. You need to create at least one character called "Administrators".

As you build and delete roles, be aware that the Role Manager feature does not allow you to create duplicate roles. Also note that, by default, the Role Manager does not allow you to delete the populated roles.

Sub Btncreaterole_click (ByVal sender as Object, ByVal e as System.EventArgs)
Dim rolename as String = Txtcreaterole.text

Try
Roles.createrole (rolename)
Lblresults.text = Nothing
Lblresults.visible = False
Txtcreaterole.text = Nothing
Catch ex as Exception
Lblresults.text = "Could not create": "+ Server.HTMLEncode" (ex. Message)
Lblresults.visible = True
End Try
End Sub

Sub Btndeleterole_click (ByVal sender as Object, ByVal e as System.EventArgs)
If (Lbxavailableroles.selectedindex <>-1) Then
Try
Roles.deleterole (Lbxavailableroles.selectedvalue)

Lblresults.text = Nothing
Lblresults.visible = False
Catch ex as Exception
Lblresults.text = "Could not deletes the role:" + Server.HTMLEncode (ex. Message)
Lblresults.visible = True
End Try
End If
End Sub
   adding users to roles and removing users from roles

The following example uses the role established in the previous example, which demonstrates how to add a user to a role and remove a user from the role. Use the Roles.addusertorole method to add users to the role, using the Roles.removeuserfromrole method to remove users from the role. Before you add a user to a role, check to see if the user is already a member of the role. This check is necessary because the role manager throws an exception if you try to add the same user to the role multiple times. In the previous example, the role information and members of the role are displayed in the data-bound control. The list of roles to which the user belongs is obtained by the Roles.getrolesforuser method. To run the following example, be sure to add yourself to the "Administrators" role.

Sub Btnaddusertorole_click (ByVal sender as Object, ByVal e as System.EventArgs)
If (Lbxavailableroles.selectedindex <>-1) Then
Dim selectedrole as String = Lbxavailableroles.selectedvalue

If not Roles.isuserinrole (selectedrole) Then
Try
Roles.addusertorole (User.Identity.Name, Selectedrole)
Refreshcurrentroleslistbox ()
Catch ex as Exception
Lblresults.text = "Could not add": "+ Server.HTMLEncode" (ex. Message)
Lblresults.visible = True
End Try
Else
Lbxavailableroles.selectedindex =-1
End If
End If
End Sub

Sub Btndeleteuserfromrole_click (ByVal sender as Object, ByVal e as System.EventArgs)
Dim selectedrole as String = Lbxuserroles.selectedvalue

If (Lbxuserroles.selectedindex <>-1) Then
Try
Roles.removeuserfromrole (User.Identity.Name, Selectedrole)
Refreshcurrentroleslistbox ()
Catch ex as Exception
Lblresults.text = "Could not remove the user": "+ Server.HTMLEncode" (ex. Message)
Lblresults.visible = True
End Try
End If
End Sub

   grant access to a page with the Role Manager

The web.config file for this example contains the <authorization> element, which restricts the sample from being accessible only to members of the "Administrators" role. Make sure you have established the "Administrators" role and added yourself to the role. Once you're called a member of the "Administrators" role, you can access the sample page. Asp. NET provides a role manager HttpModule that automatically attaches RolePrincipal to the HttpContext of the current request. If you are a member of the "Administrators" role, When the URL authorization process performs a IsInRole check based on RolePrincipal (the URL authorization process calls Roleprincipal.isinrole), the Access check returns TRUE and you can access the page. Note that you can refer to the RolePrincipal in the page by calling Page.User and converting the result to RolePrincipal.

<location path= "Administrators_role"
<system.web>
<authorization>
<allow roles= "Administrators"/>
<deny users= "*"/>
</authorization>
</system.web>
</location>
   Programmatic Check Authorization

Because the Role Manager feature attaches RolePrincipal to HttpContext, you can also write code to perform an access check based on RolePrincipal. You first set up two roles, "Regular users" and "Power Users", to add yourself to both roles. When you run the example, the page performs a isinrole check using a variety of techniques. Some access checks use the User.IsInRole. It shows that RolePrincipal is also available when using the normal page.user syntax. This page also demonstrates how to convert Page.User to a RolePrincipal reference, and then directly increase the use of IsInRole in RolePrincipal.

<asp:label id= "Label1" runat= "Server" text=<%# user.isinrole ("Administrators")%>/>
<asp:label id= "Label2" runat= "Server" text=<%# roles.isuserinrole ("Regular Users")%>/>
<asp:label id= "Label3" runat= "Server" text=<%# (CType (User,roleprincipal)). IsInRole ("Power Users")%>/>



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.