Está en la página 1de 27

An important part of many Web applications is the ability to identify users and control access to

resources. The act of determining the identity of the requesting entity is known as authentication.
Generally, the user must present credentials, such as a name/password pair in order to be
authenticated. Once an authenticated identity is available, it must be determined whether that
identity can access a given resource. This process is known as authorization. ASP.NET works in
conjunction with IIS to provide authentication and authorization services to applications.

An important feature of COM objects is the ability to control the identity under which COM
object code is executed. When a COM object executes code with the identity of the requesting
entity, this is known as impersonation. ASP.NET Framework applications can optionally choose
to impersonate requests.

Some applications also want to be able to dynamically tailor content, based on the requesting
identity or based on a set of roles that a requesting identity belongs to. ASP.NET Framework
applications can dynamically check whether the current requesting identity participates in a
particular role. For example, an application might want to check to see whether the current user
belongs to the manager's role, in order to conditionally generate content for managers.

The ASP.NET 2.0 Membership feature facilitates the creation and management of users. The
Membership feature works in conjunction with another new feature called Role Manager. Role
Manager provides the infrastructure for creating roles and assigning users to roles. When the
Membership and Role Manager features are used in conjunction with Forms Authentication,
ASP.NET 2.0 provides end-to-end support for creating, authenticating and authorizing users.

Both Membership and Role Manager have been designed with a provider-based model. Providers
abstract the physical data storage for a feature from the classes and business logic exposed by a
feature. Both Membership and Role Manager ship with providers for Microsoft™ SQL Server.
Membership also ships with a provider that works against Active Directory and Active Directory
Application Mode (ADAM). Role Manager ships with an additional provider that works with the
Authorization Manager feature available in Windows Server 2003. You can create your own
custom providers and configure them to work either the Membership or Role Manager features.
Pages that use the Membership and Role Manager features will continue to work unchanged with
your custom providers.

The Login Controls are a set of custom server controls that provide common user interfaces for
authentication and authorization tasks. The Login Controls use the functionality in the
Membership, Role Manager, and Forms Authentication features.

Authentication and Authorization


ASP.NET works in conjunction with IIS to support authentication, using Basic, Digest, and
Windows authentication. ASP.NET supports the Microsoft Passport authentication service, which
provides single sign-on services and support for user profile services. ASP.NET also provides a
robust service for applications that want to use forms-based authentication. Forms-based
authentication uses cookies to authenticate users and allows the application to do its own
credential verification.
It is important to realize that ASP.NET authentication services are subject to the authentication
services provided by IIS. For example, in order to use Basic authentication in an IIS application,
you must configure the use of Basic authentication for the application using the Internet Service
Manager tool.

ASP.NET provides two types of authorization services:

 Checks against ACLs or permissions on a resource to determine whether the


authenticated user account can access the resources
 URL authorization, which authorizes an identity for pieces of the Web space

To illustrate the difference, consider a scenario in which an application is configured to allow


anonymous access using the IUSR_MYMACHINE account. When a request for an ASP.NET page
(such as "/default.aspx") is authorized, a check is done against the ACLs on that file (for
example, "c:\inetpub\wwwroot\default.aspx") to see whether the IUSR_MYMACHINE account
has permission to read the file. If it does, then access is authorized. If the web content resides on
an NTFS volume, and Windows Authentication is configured for the virtual directory, file
authorization is performed automatically.

For URL authorization, the anonymous user is checked against the configuration data computed
for the ASP.NET application. If access is allowed for the requested URL, the request is
authorized. In this case, ASP.NET checks to see whether the anonymous user has access to
/Default.aspx (that is, the check is done against the URL itself, not against the file that the URL
ultimately resolves to).

This might seem a subtle distinction, but it enables applications to use authentication schemes
likes forms-based authentication or Passport authentication, in which the users do not correspond
to a machine or domain account. It also enables authorization against virtual resources, for which
there is no physical file underlying the resource. For example, an application could choose to
map all requests for files ending in .stk to a handler that serves stock quotes based on variables
present in the query string. In such a case, there is no physical .stk against which to do ACL
checks, so URL authorization is used to control access to the virtual resource.

File authorization is always performed against the authenticated account provided by IIS. If
anonymous access is allowed, this is the configured anonymous account. Otherwise, it uses an
NT account. This works in exactly the same way as ASP.

File ACLs are set for a given file or directory using the Security tab in the Explorer property
page. URL authorization is configured as part of an ASP.NET Framework application and is
described fully in Authorizing Users and Roles.

To activate an ASP.NET authentication service, you must configure the <authentication>


element in the application's configuration file. This element can have any of the values listed in the
following table.

Value Description
No ASP.NET authentication services are active. Note that IIS
None
authentication services can still be present.
ASP.NET authentication services attach a WindowsPrincipal
Windows (System.Security.Principal.WindowsPrincipal) to the current
request to enable authorization against NT users or groups.
ASP.NET authentication services manage cookies and redirect
unauthenticated users to a logon page. This is often used in
Forms
conjunction with the IIS option to allow anonymous access to an
application.
ASP.NET authentication services provide a convenient wrapper
Passport around the services provided by the Passport SDK, which must be
installed on the machine.

For example, the following configuration file enables forms-based (cookie) authentication for an
application:

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

Windows-based Authentication
When you use ASP.NET Windows authentication, ASP.NET attaches a WindowsPrincipal
object to the current request. This object is used by URL authorization. The application can also
use it programmatically to determine whether a requesting identity is in a given role.

If User.IsInRole("Administrators") Then
DisplayPrivilegedContent()
End If
VB

The WindowsPrincipal class determines roles by NT group membership. Applications that want
to determine their own roles can do so by handling the
WindowsAuthentication_OnAuthenticate event in their Global.asax file and attaching their
own class that implements System.Security.Principal.IPrincipal to the request, as shown in the
following example:

' Create a class that implements IPrincipal


Public Class MyPrincipal : Inherits IPrincipal
' Implement application-defined role mappings
End Class

' In a Global.asax file


Public Sub WindowsAuthentication_OnAuthenticate(Source As Object, e As
WindowsAuthenticationEventArgs)
' Attach a new application-defined class that implements IPrincipal to
' the request.
' Note that since IIS has already performed authentication, the provided
' identity is used.
e.User = New MyPrincipal(e.Identity)
End Sub
VB

The following sample shows how to access the name of an authenticated user, which is available
as User.Identity.Name. Programmers familiar with ASP should note that this value is also still
available as the AUTH_USER server variable. Prior to running this application, make sure the
settings in IIS are set to require only Integrated Windows authentication for the sample
application. This will force a security handshake between the browser and the sample
application.

Forms-based Authentication
Forms-based authentication is an ASP.NET authentication service that enables applications to
provide their own logon UI and do their own credential verification. ASP.NET authenticates
users, redirects unauthenticated users to the logon page, and performs all the necessary cookie
management. This sort of authentication is a popular technique used by many Web sites.

An application has to be configured to use forms-based authentication by setting


<authentication> to Forms, and denying access to anonymous users. The following example
shows how this can be done in the Web.config file for the desired application:
<configuration>
<system.web>
<authentication mode="Forms"/>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
Administrators use forms-based authentication to configure the name of the cookie to use, the
protection type, the URL to use for the logon page, length of time the cookie is in effect, and the
path to use for the issued cookie. The following table shows the valid attributes for the <Forms>
element, which is a sub-element of the <authentication> element shown in the following
example:
<authentication mode="Forms">
<forms name=".ASPXCOOKIEDEMO" loginUrl="login.aspx"
defaultUrl="default.aspx"
protection="All" timeout="30" path="/" requireSSL="false"
slidingExpiration="true" enableCrossAppRedirects="false"
cookieless="UseDeviceProfile" domain="">
<!-- protection="[All|None|Encryption|Validation]" -->
<!-- cookieless="[UseUri | UseCookies | AutoDetect |
UseDeviceProfile]" -->
</forms>
</authentication>
Attribute Description
ASP.NET 2.0 Forms Authentication can store the forms
authentication ticket in either a cookie, or in a cookie-less
representation on the URL. The default value of UseDeviceProfile
means that ASP.NET determines where to store the ticket based on
cookieless
pre-computed browser profiles. The AutoDetect option causes
ASP.NET to dynamically determine if the browser supports cookies
or not. UseUri and UseCookies force cookieless and cookied tickets
respectively.
Specifies the default URL to which the request is redirected after a
defaultUrl successful login. This value is used if a redirect URL is not available
to Forms Authentication when redirecting after login.
Specifies the value of the Domain property on the HttpCookie
containing the forms authentication ticket. Explicitly setting this
attribute allows applications to share the same cookie as long as the
domain
applications share a common portion of a DNS namespace (e.g.
appA.contoso.com and appB.contoso.com could share a cookie if the
domain attribute is set to "contoso.com").
In ASP.NET 2.0, Forms Authentication allows you to pass the forms
authentication ticket across applications in either a query-string
enableCrossAppRedirects variable or in a forms POST variable. Setting this attribute to true
enables the FormsAuthenticationModule to extract the ticket from
either the query-string or forms POST variables.
Specifies the URL to which the request is redirected for
unauthenticated users. This can be on the same computer or a remote
loginUrl one. If it is on a remote computer, both computers need to be using
the same value for the decryptionkey and validationKey attributes
found in the machineKey configuration element.
Name of the HTTP cookie to use for authentication purposes. Note
that if more than one application wants to use forms-based
authentication services on a single computer, and each application
wants the forms authentication cookie to be isolated by application,
name
then they should each configure a unique cookie value. In order to
avoid causing dependencies in URLs, ASP.NET also uses "/" as the
Path value when setting authentication cookies, so that they are sent
back to every application on the site.
path Path to use for the issued cookie. The default value is "/" to avoid
difficulties with mismatched case in paths, since browsers are strictly
case-sensitive when returning cookies. Applications in a shared-
server environment should use this directive to maintain private
cookies. (Alternatively, they can specify the path at runtime using the
APIs to issue cookies.)
Method used to protect cookie data. Valid values are as follows:
 All: Use both data validation and encryption to protect the
cookie. The configured data validation algorithm is based on
the <machinekey> element. AES is used by default for
encryption, and if the key is long enough (48 characters). All
is the default (and suggested) value.
 None: Use for sites that are only using cookies for
personalization and have weaker security requirements. Both
encryption and validation can be disabled. Although you
should use caution if you use cookies in this way, this setting
protection provides the best performance of any method of doing
personalization using the .NET Framework.
 Encryption: Encrypts the cookie using AES, TripleDES or
DES, but data validation is not done on the cookie. This type
of cookie can be subject to chosen plaintext attacks.

 Validation: Does not encrypt the contents of the cookie, but


validates that the cookie data has not been altered in transit.
To create the cookie, the validation key is concatenated in a
buffer with the cookie data and a MAC is computed and
appended to the outgoing cookie.
If set to true, Forms Authentication sets the secure bit on the forms
authentication cookie. Compliant browers will only send the cookie
requireSSL
back to ASP.NET over an SSL connection. Note that this setting has
no effect when using cookieless forms authentication.
If set to true, Forms Authentication will periodically update the time
to live for the forms authentication ticket. This occurs regardless of
slidingExpiration
whether or not the ticket is contained in a cookie, or in a cookieless
format on the URL.
Amount of time in integer minutes, after which the cookie expires.
The default value is 30. The timeout attribute is a sliding value,
expiring n minutes from the time the last request was received. In
timeout order to avoid adversely affecting performance and to avoid multiple
browser warnings for those who have cookies warnings turned on,
the cookie is updated if the time is more than half gone. (This means
a loss of possible precision in some cases.)

After the application has been configured, you need to provide a logon page. The following
example shows a simple logon page. When the sample is run, it requests the Default.aspx page.
Unauthenticated requests are redirected to the logon page (Login.aspx), which presents a simple
form that prompts for an e-mail address and a password. (Use
Username="someone@www.contoso.com" and Password="password" as credentials.)

After validating the credentials, the application calls the following:


FormsAuthentication.RedirectFromLoginPage(UserEmail.Value,
PersistCookie.Checked)
VB

This redirects the user back to the originally requested URL. Applications that do not want to
perform the redirection can call either FormsAuthentication.GetAuthCookie to retrieve the
cookie value or FormsAuthentication.SetAuthCookie to attach a properly encrypted cookie to
the outgoing response. These techniques can be useful for applications that provide a logon UI
embedded in the containing page or that want to have more control over where users are
redirected.

Authentication cookies can either be temporary or permanent ("persistent"). Temporary cookies


last only for the duration of the current browser session. When the browser is closed, the cookie
is lost. Permanent cookies are saved by the browser and are sent back across browser sessions
unless explicitly deleted by the user or if the cookie lifetime expires. The cookie lifetime for both
temporary and permanent cookies is determined by the timeout configuration attribute. This is a
slight change in behavior from older versions of ASP.NET where the persistent cookies were
given a lifetime of 50 years. In ASP.NET 2.0, both temporary and persistent cookies have their
expiration date set to the current time plus the value of the timeout configuration attribute.

VB Forms-Based/Cookie Authentication

The authentication cookie used by forms authentication consists of a serialized version of the
System.Web.Security.FormsAuthenticationTicket class. The information includes the user
name (but not the password), the version of forms authentication used, the date the cookie was
issued, and a field for optional application-specific data.

Application code can revoke or remove authentication cookies using the


FormsAuthentication.SignOut method. This removes the authentication cookie regardless of
whether it is temporary or permanent.

It is also possible to supply forms-based authentication services with a list of valid credentials
using configuration, as shown in the following example:
<authentication>
<credentials passwordFormat="SHA1" >
<user name="Mary"
password="94F85995C7492EEC546C321821AA4BECA9A3E2B1"/>
<user name="John"
password="5753A498F025464D72E088A9D5D6E872592D5F91"/>
</credentials>
</authentication>
You can generate the hashed representation of the password by using the
FormsAuthentication.HashPasswordForStoringInConfigFile(String password, String
passwordFormat)API. This method supports generating hashed values using either SHA1 or
MD5. The application can then call FormsAuthentication.Authenticate, supplying the
username and password, and ASP.NET will verify the credentials. Credentials can be stored in
cleartext, or as SHA1 or MD5 hashes, according to the following values of the passwordFormat
attribute:

Hash Type Description


Clear Passwords are stored in cleartext
SHA1 Passwords are stored as SHA1 digests
MD5 Passwords are stored as MD5 digests

Authorizing Users and Roles


ASP.NET is used to control client access to URL resources. It is configurable for the HTTP
method used to make the request (GET or POST) and can be configured to allow or deny access
to groups of users or roles. The following example shows access being granted to a user named
someone and a role named Admins. All other users are denied access.
<authorization>
<allow users="someone@www.contoso.com" />
<allow roles="Admins" />
<deny users="*" />
</authorization>
Permissible elements for authorization directives are either allow or deny. Each allow or deny
element must contain a users or a roles attribute. Multiple users or roles can be specified in a
single element by providing a comma-separated list.
<allow users="John,Mary" />

The HTTP method can be indicated using the Verb attribute:

<allow VERB="POST" users="John,Mary" />


<deny VERB="POST" users="*" />
<allow VERB="GET" users="*" />
This example lets Mary and John POST to the protected resources, while only allowing
everyone else to use GET.

There are two special usernames:

UserName Description
* All users
? Anonymous (unauthenticated) users
These special usernames are commonly used by applications using forms-based authentication to
deny access to unauthenticated users, as shown in the following example:
<authorization>
<deny users="?" />
</authorization>
URL authorization is computed hierarchically and the rules used to determine access are as
follows:
 Rules relevant to the URL are collected from across the hierarchy and a merged list of
rules is constructed.
 The most recent rules are placed at the head of the list. This means that configuration in
the current directory is at the head of the list, followed by configuration in the immediate
parent, and so on, up to the top-level file for the computer.
 Rules are checked until a match is found. If the match is allowable, access is granted. If
not, access is disallowed.

What this means is that applications that are not interested in inheriting their configuration
should explicitly configure all of the possibilities relevant to their applications.

The default setting in the machine-wide configuration file (machine.config) is to grant access to
all users. Unless an application is configured to the contrary (and assuming that a user is
authenticated and passes the file authorization ACL check), access is granted.

When roles are checked, URL authorization effectively marches down the list of configured roles
and does something that looks like the following pseudocode:

If User.IsInRole("ConfiguredRole") Then
ApplyRule()
End If
VB

What this means for your application is that you use your own class that implements
System.Security.Principal.IPrincipal to provide your own role-mapping semantics, as
explained in Windows-based Authentication.

The following sample uses forms-based authentication services. It explicitly denies access to
someone@www.contoso.com and anonymous users. Try logging into the sample with
Username="someone@www.contoso.com" and Password="password". Access will be denied
and you will be redirected back to the logon page. Now log on as
Username="someone.else@www.contoso.com" and Password="password". You will see that
access is granted.

VB Forms-Based/Cookie Authentication with URL Authorization

User Account Impersonation


As mentioned in the Security Overview, impersonation is the ability of a thread to execute in a
security context different from that of the process owning the thread. What this means for a Web
application is that if a server is impersonating, it is doing work using the identity of the client
making the request.

By default, ASP.NET does not do per-request impersonation. This is different from ASP, which
does impersonate on every request. If desired, you can configure an application to impersonate
on every request with the following Configuration directive:

<identity impersonate="true" />

Since ASP.NET does dynamic compilation, enabling impersonation requires that all accounts
have read/write access to the application's Codegen directory (where dynamically compiled
objects are stored by the ASP.NET runtime) as well as the global assembly cache (%Windir
%\assembly). Some applications require impersonation to be enabled for ASP compatibility or to
use Windows authentication services.

Using the Login Controls


The following examples demonstrate how to use the login controls in an application.

Creating and Logging In a User


In this example we see a home page of a website which includes a LoginStatus control that prompts the
user to login to the website. The LoginStatus control on this page determines that the user is not
currently authenticated and displays a Login link to the user. Clicking on this link takes the user to the
default login.aspx page which is configured in the forms authentication section of web.config. The Login
control is displayed on the Login.aspx page. (Note: The login control's VisibleWhenLoggedIn property is
ignored on the default login page.) In this example, the login control sets additional properties to display
the Create User link, clicking this link takes the user to another page where the CreateUserWizard
control is used. By default the CreateUserWizard control is a two step process, on the first step a user
enters the required information and when they click the create user button the control passes the
information to the membership API. If the user can not be created by the membership API an
appropriate error message is shown within the control or if the user is created they the control loads the
second step in the wizard. In this example the ContinueDestinationPageUrl property has been set to
return the user to the home page once they have been created. By default the CreateUserWizard control
authenticates or �logs-in� users when they are successfully created. When a user is returned to the
homepage they will notice that the LoginStatus control has detected that they are now authenticated
and displays a logout link. Clicking on the logout link causes the user's authentication ticket to be cleared
and toggles the display to the login link. At this point the user can click the login link, and since they have
already created a user account, they can enter their username and password on the login.aspx to login
to the website. You will notice that the Login control displays a remember me checkbox. Checking this
box and successfully logging in will cause a persistent cookie to be written to the user's machine, with a
default expiry of 50 years. You can disable this option in the Login control by setting the
DisplayRememberMe and the RememberMeSet properties are set to false. By reviewing the source for
this example you will see that no code was written and that very few properties were set to enable this
entire scenario. Style properties for these controls were set via a stylesheet applied to the site.

VB LoginStatus, Login and CreateUserWizard

Displaying Different Content for Authenticated Users


This sample illustrates how to use a LoginView control to display different content for authenticated and
anonymous users. Although, not shown in this example the LoginView control also supports displaying
different content based on a user's role. The AnonymousTemplate in the LoginView control contains a
login control and the LoggedInTemplate contains the LoginName control. The LoginName controls takes
advantage of the formatstring property to display Welcome, followed by the user's name. To see both
templates login to the site using a previously created user account or create a new account, to return to
the anonymous content click the Logout link at the top of the page.

VB LoginView and LoginName

Changing a Password
The ChangePassword control by default requires the user to be authenticated on the site prior to
changing their password. However, in this example we have set the DisplayUserName property to true,
as a result a user can be authenticated by the ChangePassword control prior to changing their password
or a user who is already authenticated on the site can enter a different user account and authenticate as
that user prior to changing their password. The sample also links to a CreateUser page that will let you
create a valid user to test this scenario.

VB ChangePassword

Using the Membership and Role Manager APIs


Membership
The Membership feature is built around two central classes: Membership and MembershipUser. The
Membership class provides methods for creating users (represented by the MembershipUser class), as
well as common administrative methods for managing users. The users that are created with the
Membership class represent the authenticated identities for an ASP.NET application.

Common tasks that you perform with the Membership class include:

 Creating a new MembershipUser


 Validating a username-password combination when a user attempts to log in. You can then use
Forms Authentication to issue a cookie indicating that a user has logged in to a site.

 Retrieving a MembershipUser instance

 Updating a MembershipUser instance

 Searching for users based on various search criteria

 Getting the count of authenticated users that are currently online

 Deleting users from the system when they are no longer needed

Once you have obtained a MembershipUser instance, the common tasks that you perform directly with
the MembershipUser class include:
 Accessing the properties on the MembershipUser class in your application
 Retrieving a user's password (only if the Membership feature is configured to allow password
retrieval)

 Changing a user's password or resetting a user's password

 Changing a user's password question and password answer (if the Membership feature has been
configured to prompt a user for a password question and answer prior to retrieving or updating
a password).

 Unlocking a user that has been locked out due to bad passwords or bad password answers.

Role Manager
The central management class for Role Manager is the Roles class. The Roles class provides methods for
creating roles and assigning users to roles. It also provides common administrative methods for
managing role information.

Common tasks that you perform with the Roles class include:

 Creating a new role


 Deleting an existing role

 Assigning users to roles

 Removing users from roles

 Determining if a user is authorized to a specific role


 Searching for users in a specific role, as well as retrieving all users in a role

 Getting the role information for a specific user

The Role Manager feature also includes an HttpModule. This module is responsible for retrieving role
assignments for a user and storing this information inside of a RolePrincipal that is available on the
HttpContext for a page. The existence of a RolePrincipal on the HttpContext allows you to secure
pages and directories using the <authorization> element. Depending on the role information stored
in the RolePrincipal, a user can be authorized for only specific pages and directories within a site.

Examples
The following samples demonstrate how to use the Membership API in an application.

Creating a New User


The following sample demonstrates how to create a new MembershipUser. This sample uses the
Membership.CreateUser overload that returns a status parameter. Other overloads are available that
throw exceptions as opposed to returning a status code. Note that by default, the Membership feature
requires passwords to be at least seven characters long, and the password must contain at least one
non-alphanumeric character.

VB Creating a User Using Membership

User Login and Accessing User Properties


The following sample demonstrates user login with the Membership.ValidateUser method. It also
demonstrates how to use Forms Authentication with Membership when logging in a user. With the user
account created in the previous sample, enter your credentials on the login page. Once you are logged in
you will be redirected to a page that uses Membership.GetUser to retrieve the MembershipUser
instance corresponding to the logged in user. Also notice that the page that displays user properties has
been placed in a directory that only allows access to authenticated users. Click the logout link at the
bottom of the page to log yourself out.

VB Login and Viewing User Properties

Updating User Properties


Login again using the credentials that were created earlier. The page displays the user properties with
the DetailsView control that is new in ASP.NET 2.0. The DetailsView control communicates with a data
source control. In this example, an ObjectDataSource control is used to retrieve the contents of a
MembershipUser instance. You can click on the Edit link at the bottom of the page to toggle the
DetailsView into edit mode. Both the email and comment for the MembershipUser can be changed.
When you want to save the new values to the database, click on the Update link. Notice in the code that
the page implements the ItemUpdating event that is raised by the ObjectDataSource. This is
necessary because the MembershipUser class does not have a parameter-less constructor, which is a
requirement to use automatic two-way databinding with ObjectDataSource. Click the logout link at the
bottom of the page to log yourself out.

VB Updating User Properties

Account Lockouts
The Membership feature automatically tracks the number of bad password attempts that occur during
login. It also tracks the number of bad password answers that are supplied when either retrieving a
password or attempting to reset a password. This sample demonstrates the automatic account lockout
ability, as well as how to unlock a user once the account is locked out. First create a new user account
using the Creating a New User sample. Next, click on the button below to run the Account Lockout
sample. The login page displays the number of bad login attempts you will need to make in order to lock
yourself out. On the login page, use the first account you created, and intentionally enter a bad
password. Continue to use a bad password for the number of times indicated on the login page. Notice
that after making the appropriate number of bad login attempts, if you then use the correct password,
you still cannot login - this is because the Membership feature automatically locked the account out after
the appropriate number of bad login attempts occurred. In order to unlock the user account, login with
the second user account that you just created. The page that is displayed is very similar to the previous
sample that displayed user properties. However, this page allows you to enter an arbitrary username in
the textbox at the bottom of the page. Enter the username for the locked out account into this textbox
and hit the Enter key. The DetailsView control will refresh and show the information for this user. Notice
that the checkbox IsLockedOut for the lockout status is checked. The LastLockoutDate has also
been updated to indicate when the user was locked out. Click the unlock button at the bottom of the
page to unlock the currently displayed user. This will call the UnlockUser method on the
MembershipUser instance, thus unlocking the user account. After unlocking the user, the IsLockedOut
checkbox has been cleared, and the LastLockoutDate property has been reset. Click the logout link at
the bottom of the page. Now attempt to login with the first user account. Notice that you can now login
successfully again.

VB Account Lockout

Deleting a User
You can delete a user with the Membership.DeleteUser method. The following sample demonstrates
deleting the currently logged in user and then logging the user out with Forms Authentication.
VB Deleting A User

Managing Roles
The following samples demonstrate the Role Manager feature using roles with an authenticated user. All
of the sample pages deny access to anonymous users. If you have not already done so, create a new user
with the Creating a New User sample. By default the Role Manager feature is not enabled in ASP.NET.
However, the web.config used in the following samples explicitly enables the Role Manager feature.

Adding and Deleting Roles


The following sample demonstrates how to create and delete roles using the Roles.CreateRole and
Roles.DeleteRole methods. After you create a new role, or delete an existing role, the page uses the
Roles.GetAllRoles method to display the available roles in the system. The return value from
Roles.GetAllRoles can be easily bound to any control that supports databinding. For the last sample,
you will want to create at least one role called "Administrators".

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

VB Adding And Deleting Roles

Adding a User to a Role and Deleting a User from a Role


Using the roles that you previously created, this sample demonstrates how to add a user to a role and
how to remove a user from a role. A user is added to a role with the Roles.AddUserToRole method,
while a user is removed from a role with the Roles.RemoveUserFromRole method. Prior to adding a
user to a role, a check is made to ensure that the user is not already a member of the role. This check is
performed because Role Manager throws an exception if you attempt to add a user more than once to a
role. As with the previous sample, role information and role membership is displayed using data-bound
controls. The list of roles that a user belongs to is retrieved with the Roles.GetRolesForUser
method. For the next sample to work, make sure to add yourself to the "Administrators" role.

VB Adding And Deleting Users To/From Roles

Authorizing Access to a Page with Role Manager


The web.config file for this sample contains an <authorization> element restricting access to
members of the "Administrators" role. If you have not already done so, make sure to create a role called
"Administrators" and add yourself to that role. Once you are a member of the "Administrators" role, you
will be able to reach the sample page. ASP.NET provides a Role Manager HttpModule that automatically
attaches a RolePrincipal to the HttpContext of the current request. If you are a member of the
"Administrators" role, when Url authorization performs an IsInRole check against the RolePrincipal
(Url authorization calls RolePrincipal.IsInRole), the access check returns true and you are
allowed to access the page. Note that you can reference a RolePrincipal in your page by calling
Page.User and casting the result to a RolePrincipal.

VB Authorizing Access To a Page For A Role

Programmatically Checking Authorization


Because the Role Manager feature attaches a RolePrincipal to the HttpContext, you can also write
code to perform access checks against the RolePrincipal. If you have not already done so, make sure to
create two additional roles called "Regular Users" and "Power Users". Add yourself to these roles as well.
When you run the sample, the page performs IsInRole checks using a variety of techniques. Some
access checks are made using User.IsInRole. This demonstrates that the RolePrincipal is available
using the normal Page.User syntax. The page also demonstrates casting Page.User to a RolePrincipal
reference, and then calling IsInRole directly on the RolePrincipal.

VB Programmtic Authorization

How to: Implement Simple Forms Authentication


.NET Framework 4

Other Versions

37 out of 56 rated this helpful - Rate this topic

The example in this topic presents a simple implementation of ASP.NET forms authentication. It
illustrates the fundamentals of how to use forms authentication to log users into an ASP.NET
application.
Note

A convenient way to work with forms authentication is to use ASP.NET membership and
ASP.NET login controls. ASP.NET membership provides a way to store and manage user
information and includes methods to authenticate users. ASP.NET login controls work with
ASP.NET membership and encapsulate the logic required to prompt users for credentials, validate
users, recover or replace passwords, and so on. In effect, ASP.NET membership and ASP.NET
login controls provide a layer of abstraction over forms authentication and replace most or all of
the work you would normally have to do to use forms authentication. For more information, see
Managing Users by Using Membership and ASP.NET Login Controls Overview.

In the scenario for the example, users request a protected resource, namely a page named
Default.aspx. Only one user has access to the protected resource: jchen@contoso.com, whose
password is "37Yj*99P". The user name and password are hard-coded into the Logon.aspx file.
The example requires three files: the Web.config file, a page named Logon.aspx, and a page
named Default.aspx. The files reside in the application root directory.

A Visual Studio project with source code is available to accompany this topic: Download.

To configure the application for forms authentication

1. If the application has a Web.config file in the application root, open it.
2. If the application does not already have a Web.config file in the application root folder,
create a text file named Web.config and add the following elements to it:

3. <?xml version="1.0"?>
4. <configuration
xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
5. <system.web>
6.
7. </system.web>
8. </configuration>
9. Within the system.web element, create an authentication element and set its mode
attribute to Forms, as shown in the following example:

10. <system.web>
11. <authentication mode="Forms">
12. </authentication>
13. </system.web>
14. Within the authentication element, create a forms element and set the following
attributes:

o loginUrl Set to "Logon.aspx." Logon.aspx is the URL to use for redirection if


ASP.NET does not find an authentication cookie with the request.

o name Set to ".ASPXFORMSAUTH". This sets the suffix for the name of the
cookie that contains the authentication ticket.
15. <system.web>
16. <authentication mode="Forms">
17. <forms loginUrl="Logon.aspx" name=".ASPXFORMSAUTH">
18. </forms>
19. </authentication>
20. </system.web>
21. Within the system.web element, create an authorization element.

22. <system.web>
23. <authentication mode="Forms">
24. <forms loginUrl="Logon.aspx" name=".ASPXFORMSAUTH">
25. </forms>
26. </authentication>
27. <authorization>
28. </authorization>
29. </system.web>
30. Within the authorization element, create a deny element and set its users attribute to "?".
This specifies that unauthenticated users (represented by "?") are denied access to
resources in this application.

31. <system.web>
32. <authentication mode="Forms">
33. <forms loginUrl="logon.aspx" name=".ASPXFORMSAUTH">
34. </forms>
35. </authentication>
36. <authorization>
37. <deny users="?" />
38. </authorization>
39. </system.web>
40. Save the Web.config file and close it.

Creating the Logon Page

When users request any page from the Web site and if they have not previously been
authenticated, they are redirected to a page named Logon.aspx. You specified this file name
earlier in the Web.config file.

The Logon.aspx page collects user credentials (e-mail address and password) and authenticates
them. If the user is successfully authenticated, the logon page redirects the user to the page they
originally requested. In the example, the valid credentials are hard-coded into the page code.

Security Note

This example contains a text box that accepts user input, which is a potential security threat. By
default, ASP.NET Web pages validate that user input does not include script or HTML elements.
For more information, see Script Exploits Overview.
To create the logon page

1. Create an ASP.NET page named Logon.aspx in the application root folder.


2. Copy the following markup and code into it:

VB

<%@ Page Language="VB" %>


<%@ Import Namespace="System.Web.Security" %>

<script runat="server">
Sub Logon_Click(ByVal sender As Object, ByVal e As EventArgs)
If ((UserEmail.Text = "jchen@contoso.com") And _
(UserPass.Text = "37Yj*99Ps")) Then
FormsAuthentication.RedirectFromLoginPage _
(UserEmail.Text, Persist.Checked)
Else
Msg.Text = "Invalid credentials. Please try again."
End If
End Sub
</script>

<html>
<head id="Head1" runat="server">
<title>Forms Authentication - Login</title>
</head>
<body>
<form id="form1" runat="server">
<h3>
Logon Page</h3>
<table>
<tr>
<td>
E-mail address:</td>
<td>
<asp:TextBox ID="UserEmail" runat="server" /></td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ControlToValidate="UserEmail"
Display="Dynamic"
ErrorMessage="Cannot be empty."
runat="server" />
</td>
</tr>
<tr>
<td>
Password:</td>
<td>
<asp:TextBox ID="UserPass" TextMode="Password"
runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
ControlToValidate="UserPass"
ErrorMessage="Cannot be empty."
runat="server" />
</td>
</tr>
<tr>
<td>
Remember me?</td>
<td>
<asp:CheckBox ID="Persist" runat="server" /></td>
</tr>
</table>
<asp:Button ID="Submit1" OnClick="Logon_Click" Text="Log On"
runat="server" />
<p>
<asp:Label ID="Msg" ForeColor="red" runat="server" />
</p>
</form>
</body>
</html>

C#

<%@ Page Language="C#" %>


<%@ Import Namespace="System.Web.Security" %>

<script runat="server">
void Logon_Click(object sender, EventArgs e)
{
if ((UserEmail.Text == "jchen@contoso.com") &&
(UserPass.Text == "37Yj*99Ps"))
{
FormsAuthentication.RedirectFromLoginPage
(UserEmail.Text, Persist.Checked);
}
else
{
Msg.Text = "Invalid credentials. Please try again.";
}
}
</script>
<html>
<head id="Head1" runat="server">
<title>Forms Authentication - Login</title>
</head>
<body>
<form id="form1" runat="server">
<h3>
Logon Page</h3>
<table>
<tr>
<td>
E-mail address:</td>
<td>
<asp:TextBox ID="UserEmail" runat="server" /></td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ControlToValidate="UserEmail"
Display="Dynamic"
ErrorMessage="Cannot be empty."
runat="server" />
</td>
</tr>
<tr>
<td>
Password:</td>
<td>
<asp:TextBox ID="UserPass" TextMode="Password"
runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
ControlToValidate="UserPass"
ErrorMessage="Cannot be empty."
runat="server" />
</td>
</tr>
<tr>
<td>
Remember me?</td>
<td>
<asp:CheckBox ID="Persist" runat="server" /></td>
</tr>
</table>
<asp:Button ID="Submit1" OnClick="Logon_Click" Text="Log On"
runat="server" />
<p>
<asp:Label ID="Msg" ForeColor="red" runat="server" />
</p>
</form>
</body>
</html>

Basic Security Practices for Web Applications


.NET Framework 4

Other Versions

14 out of 22 rated this helpful - Rate this topic


The topic of creating a secure Web application is extensive. It requires study to understand
security vulnerabilities. You also need to familiarize yourself with the security facilities of
Windows, the .NET Framework, and ASP.NET. Finally, it is essential to understand how to use
these security features to counter threats.

Even if you are not experienced with security, there are basic measures that you should take to
protect your Web application. The following list provides minimum-security guidelines that
apply to all Web applications and that you should follow:

 General Web Application Security Recommendations


 Run Applications with Least Privileges

 Know Your Users

 Guard Against Malicious User Input

 Access Databases Securely

 Create Safe Error Messages

 Keep Sensitive Information Safely

 Use Cookies Securely

 Guard Against Denial-of-Service Threats

Note

For comprehensive and detailed security guidance which will help you to design, develop,
configure, and deploy more secure ASP.NET Web applications, see the security modules
provided on the Microsoft Patterns and Practices Web site.
General Web Application Security Recommendations

Even the most elaborate application security can fail if a malicious user can use simple ways to
get to your computers. Follow these guidelines:

 Back up often and keep your backups physically secure.


 Keep your Web server computer physically secure so that unauthorized users cannot get
to it, turn it off, or take it.

 Use the Windows NTFS file system, not FAT32. NTFS offers substantially more security
than FAT32. For details, see the Windows documentation.
 Secure the Web server computer and all computers on the same network with strong
passwords.

 Secure IIS. For details, see the Microsoft TechNet Security Center Web site.

 Close unused ports and turn off unused services.

 Run a virus checker that monitors inbound and outbound traffic.

 Establish and enforce a policy that forbids users from keeping their passwords written
down in an easy-to-find location.

 Use a firewall. For recommendations, see Microsoft Firewall Guidelines on the Microsoft
security site.

 Install the latest security patches from Microsoft and other vendors. For example, the see
the Microsoft TechNet Security Center Web site has a list of the latest security bulletins
for all Microsoft products. Other vendors have similar sites.

 Use Windows event logging and examine the logs frequently for suspicious activity. This
includes repeated attempts to log on to your system and an extremely high number of
requests against your Web server.

Run Applications with Least Privileges

When your application runs, it runs within a context that has specific privileges on the local
computer and potentially on remote computers. For information on configuring the application
identity, see Configuring ASP.NET Process Identity. To run with least privileges, follow these
guidelines:

 Do not run your application with the identity of a system user (administrator).
 Run the application in the context of a user with the minimum practical privileges.

 Set permissions (Access Control Lists or ACLs) on all the resources required for your
application. Use the least permissive setting. For example, if practical in your application,
set files to be read-only. For a list of the minimum required ACL permissions required for
the identity of your ASP.NET application, see ASP.NET Required Access Control Lists
(ACLs).

 Keep files for your Web application in a folder below the application root. Do not allow
users the option of specifying a path for any file access in your application. This helps
prevent users from getting access to the root of your server.

Know Your Users


In many applications, users access the site anonymously (without having to provide credentials).
If so, your application accesses resources by running in the context of a predefined user. By
default, this context is the local ASPNET user (on Windows 2000 or Windows XP) or
NETWORK SERVICE user (on Windows Server 2003) on the Web server computer. To restrict
access to users who are authenticated, follow these guidelines:

 If your application is an intranet application, configure it to use Windows integrated


security. That way, the user's logon credentials can be used to access resources. For more
information, see ASP.NET Impersonation.
 If you need to gather credentials from the user, use one of the ASP.NET authentication
strategies. For an example, see Managing Users by Using Membership.

Guard Against Malicious User Input

As a general rule, never assume that input you get from users is safe. It is easy for malicious
users to send potentially dangerous information from the client to your application. To guard
against malicious input, follow these guidelines:

 In ASP.NET Web pages, filter user input to check for HTML tags, which might contain
script. For details, see How to: Protect Against Script Exploits in a Web Application by
Applying HTML Encoding to Strings.
 Never echo (display) unfiltered user input. Before displaying untrusted information,
encode HTML to turn potentially harmful script into display strings.

 Never store unfiltered user input in a database.

 If you want to accept some HTML from a user, filter it manually. In your filter, explicitly
define what you will accept. Do not create a filter that tries to filter out malicious input; it
is very difficult to anticipate all possible malicious input.

 Do not assume that information you get from the HTTP request header (in the
HttpRequest object) is safe. Use safeguards for query strings, cookies, and so on. Be
aware that information the browser reports to the server (user agent information) can be
spoofed, in case that is important in your application.

 If possible, do not store sensitive information in a place accessible from the browser, such
as hidden fields or cookies. For example, do not store a password in a cookie.

Note

View state is stored in a hidden field in an encoded format. By default, it includes a


message authentication code (MAC) so that the page can determine whether view state
was tampered with. If sensitive information is stored in view state, encrypt by setting the
page's ViewStateEncryptionMode property to true.
Access Databases Securely

Databases typically have their own security. An important aspect of a secure Web application is
designing a way for the application to access the database securely. Follow these guidelines:

 Use the inherent security of your database to limit who can access database resources.
The exact strategy depends on your database and your application:
o If practical in your application, use integrated security so that only Windows-
authenticated users can access the database. Integrated security is more secure
than passing explicit credentials to the database.

o If your application involves anonymous access, create a single user with very
limited permissions, and perform queries by connecting as this user.

 Do not create SQL statements by concatenating strings that involve user input. Instead,
create a parameterized query and use user input to set parameter values.

 If you must store a user name and password somewhere to use as the database login
credentials, store them in the Web.config file and secure the file with protected
configuration. For details, see Encrypting Configuration Information Using Protected
Configuration.

For more information on accessing data securely, see Securing Data Access and Securing
ADO.NET Applications.

Create Safe Error Messages

If you are not careful, a malicious user can deduce important information about your application
from the error messages it displays. Follow these guidelines:

 Do not write error messages that echo information that might be useful to malicious
users, such as a user name.
 Configure the application not to show detailed errors to users. If you want to display
detailed error messages for debugging, determine first whether the user is local to the
Web server. For details, see How to: Display Safe Error Messages.

 Use the customErrorsconfiguration element to control who can view exceptions from the
server.
 Create custom error handling for situations that are prone to error, such as database
access. For more information, see Error Handling in ASP.NET Pages and Applications.

Keep Sensitive Information Safely

Sensitive information is any information that you need to keep private. A typical piece of
sensitive information is a password or an encryption key. If a malicious user can get to the
sensitive information, then the data protected by the secret is compromised. Follow these
guidelines:

 If your application transmits sensitive information between the browser and the server,
consider using the Secure Sockets Layer (SSL). For details on how to secure a site with
SSL, see article Q307267, "HOW TO: Secure XML Web Services with Secure Socket
Layer in Windows 2000" in the Microsoft Knowledge Base at
http://support.microsoft.com.
 Use protected configuration to secure sensitive information in configuration files such as
the Web.config or Machine.config files. For more information, see Encrypting
Configuration Information Using Protected Configuration.

 If you must store sensitive information, do not keep it in a Web page, even in a form that
you think people will not be able to see it (such as in server code).

 Use the strong encryption algorithms supplied in the System.Security.Cryptography


namespace.

Use Cookies Securely

Cookies are a useful way to keep user-specific information available. However, because cookies
are sent to the browser's computer, they are vulnerable to spoofing or other malicious use. Follow
these guidelines:

 Do not store any critical information in cookies. For example, do not store a user's
password in a cookie, even temporarily. As a rule, do not keep anything in a cookie that,
if spoofed, can compromise your application. Instead, keep a reference in the cookie to a
location on the server where the information is.
 Set expiration dates on cookies to the shortest practical time you can. Avoid permanent
cookies if possible.

 Consider encrypting information in cookies.

 Consider setting the Secure and HttpOnly properties on the cookie to true.
Guard Against Denial-of-Service Threats

An indirect way that a malicious user can compromise your application is by making it
unavailable. The malicious user can keep the application too busy to service other users, or if can
simply cause the application to crash. Follow these guidelines:

 Use error handling (for example, try-catch). Include a finally block in which you release
resources in case of failure.
 Configure IIS to use process throttling, which prevents an application from using up a
disproportionate amount of CPU time.

 Test size limits of user input before using or storing it.

 Put size safeguards on database queries. For example, before you display query results in
an ASP.NET Web page, be sure that there are not an unreasonable number of records.

 Put a size limit on file uploads, if those are part of your application. You can set a limit in
the Web.config file using syntax such as the following, where the maxRequestLength
value is in kilobytes:

 <configuration>
 <system.web>
 <httpRuntime maxRequestLength="4096" />
 </system.web>
 </configuration>

También podría gustarte