How to Create a genericprincipal object using form Authentication

Source: Internet
Author: User
Content on this page
Target
Applicability
How to use this chapter
Summary
Background
Create a web application with a logon page
Configure form authentication for Web Applications
Generate an authentication ticket for Authenticated Users
Construct genericprincipal and formsidentity objects
Test the application
Other resources

Target

The goals of this chapter are:

Create a web applicationProgramThe application uses form authentication and fills in the user identity and role that passes authentication.GenericprincipalObject for. Net role-based authorization.

Back to Top

Applicability

This chapter applies to the following products and technologies:

Microsoft Windows XP, Windows 2000 Server (Service Pack 3), and later Operating Systems

Microsoft. NET Framework Version 1.0 (Service Pack 2) and later

Microsoft Visual Studio 1.0. NET and later

Microsoft Visual C #. net

Back to Top

How to use this chapter

To learn more about this chapter:

You must have experience programming with Visual C #. NET and Visual Studio. NET.

You must have experience in using the Visual Studio. NET development environment.

You must have experience developing Web applications using ASP. NET.

Read chapter 1 identity authentication and authorization. This chapter introduces the security of. Net-based roles and discussesGenericprincipalObject.

Read chapter 4 ASP. NET security. This chapter is widely introduced.GenericprincipalAnd how to use. Net role-based security in ASP. NET web applications.

Read how to use form authentication for Active Directory. This chapter provides details about how to obtain user account information from Active Directory.

Read how to use form authentication for SQL Server 2000. This chapter provides details about how to use SQL Server 2000 as a user account database.

Back to Top

Summary

When using a custom authentication mechanism that is not based on Windows accounts, you must use Microsoft. net role security, you must create your own ASP. net authentication ticket, and configureIprincipalInstance. They represent the identities and roles of authenticated users.

This chapter describes how to create a web application that uses form authentication to authenticate a user's identity and create an authentication ticket that contains user and role information. It also describes how to map this informationGenericprincipalAndFormsidentityObject to apply them to the authorization logic in the application.

Back to Top

Background

Applications that use form authentication usually need to useGenericprincipalClass (FormsidentityTo create a non-Windows-specific authorization scheme independent of the Windows domain.

For example, an application can:

Use Form authentication to obtain user creden。 (user name and password ).

Creden for data storage verification, such as database or Microsoft Active Directory.

Create based on the value retrieved from the data storageGenericprincipalAndFormsidentityObject. They may contain details about the member identities of user roles.

Use these objects for authorization decisions.

This chapter describes how to create a form-based Web application to verify the identity of a user and create a custom form authentication ticket containing user and role information. It also describes how to map this informationGenericprincipalAndFormsidentityAnd associate these new objects with the HTTP Web Request context to apply them to the authorization logic in the application.

This chapter focuses on how to constructGenericprincipalAndFormsidentityObject and form authentication ticket. For more information about how to verify user identity for Active Directory and SQL Server 2000, see the following sections in this Guide:

How to use form authentication in Active Directory

How to use form authentication in SQL Server 2000

Back to Top

Create a web application with a logon page

This process creates a new ASP. NET web application. The application will contain two pages: the login page (only accessible to authenticated users) and the login page (used to collect user creden ).

Create a web application with a logon page

1.

Start Visual Studio. NET and createGenericprincipalappThe New Visual C # ASP. NET web application.

2.

Rename webform1.aspx to logon. aspx.

3.

Add the following controls to logon. aspx to create a logon form.

Table 1: logon. aspx Control

Control Type Text ID

Tag

User name:

-

Tag

Password

-

Text Box

-

Txtusername

Text Box

-

Txtpassword

Button

Login

Btnlogon

4.

Set the Password text boxTextmodeSet propertyPassword.

5.

In Solution Explorer, right-click "genericprincipalapp", point to "add", and click "add web form ".

6.

Enter "default. aspx" as the new form name, and click "open ".

Back to Top

Configure form authentication for Web Applications

Edit the Web. config file of the application to configure form authentication for the application.

1.

Use Solution Explorer to open web. config.

2.

Search <Authentication> Element, andModeProperty changedForms.

3.

Set <Forms> Add the element as <Authentication> Set the child element of the element as follows:Loginurl,Name,TimeoutAndPathAttribute:

<Authentication mode = "forms"> <forms loginurl = "logon. aspx "name =" authcookie "timeout =" 60 "Path ="/"> </Forms> </authentication>

4.

In <Authentication> Add the following elements <Authorization> Element. In this way, Only Authenticated Users are allowed to access the application. Previously <Authentication> Element createdLoginurlThe property redirects unauthenticated requests to the logon. ASPX page.

<Authorization> <deny users = "? "/> <Allow users =" * "/> </authorization>
Back to Top

Generate an authentication ticket for Authenticated Users

This process is compiledCodeTo generate an authentication ticket for the authenticated user. The authentication ticket is ASP. NET.FormsauthenticationmoduleA cookie type.

The authentication code usually involves searching for the provided user name and password in a custom database or Active Directory.

For information on performing these searches, see the following chapters in this Guide:

How to use form authentication in Active Directory

How to use form authentication in SQL Server 2000

Generate an authentication ticket for Authenticated Users

1.

Open the logon. aspx. CS file, andUsingStatement to add existingUsingThe statement is as follows:

Using system. Web. Security;

2.

Add the following private helper Method toIsauthenticatedIn the webform1 class, this class is used to verify the user name and password to verify the user's identity. This Code assumes that all user names and passwords are valid.

Private bool isauthenticated (string username, string password) {// find the code that is omitted for clarity. // This code is usually intended for an SQL database or an Active Directory. // verify the combination of the user name and password. // simulate a user return that has passed authentication. true ;}

3.

Add the followingGetrolesPrivate helper method, which is used to obtain the user's role set:

Private string getroles (string username, string password) {// find the Code omitted for clarity. // This Code usually searches for the role list in the database table. // If the user has authenticated for Active Directory, you may use the // security group to which the user belongs and/or communication // group list // This getroles method to return a string containing the role separated by the pipeline, // instead of returning an array, because the string format is convenient // stored in the authentication ticket/cookie, as the user data returns "senior manager | employee ";}

4.

Display the logon. aspx form in designer mode, and double-click "Log on" to create an event handler.

5.

Add a pairIsauthenticatedThe user name and password captured through the login form. Assign the return value toBooleanType Variable, indicating whether the user passes authentication.

Bool isauthenticated = isauthenticated (txtusername. Text, txtpassword. Text );

6.

If the user passes authentication, add a pairGetrolesTo obtain the User Role list.

If (isauthenticated = true) {string roles = getroles (txtusername. Text, txtpassword. Text );

7.

Create a new form authentication ticket, which includes the user name, expiration time, and role list of the user. Note that the user data attribute of the authentication ticket is used to store the role list of the user. Note that the following code creates a non-permanent ticket. However, determining whether a ticket or cookie is permanently dependent on your application solution.

 // create the authentication ticket formsauthenticationticket authticket = new formsauthenticationticket (1, // version txtusername. text, // username datetime. now, // create datetime. now. addminutes (60), // false upon expiration, // permanent roles); // user data 

8.

Add code to create an encrypted string representation for the ticket and store it as data inHttpcookieObject.

// Encrypt the ticket. String encryptedticket = formsauthentication. Encrypt (authticket); // create a cookie and add the encrypted ticket to // The cookie as data. Httpcookie authcookie = new httpcookie (formsauthentication. formscookiename, encryptedticket );

9.

Add the cookie to the cookie set returned to the user's browser.

// Add the cookie to the outgoing Cookie set. Response. Cookies. Add (authcookie );

10.

Redirects the user to the page of the initial request.

// Redirect the user to the initial request page response. Redirect (formsauthentication. getredirecturl (txtusername. Text, false ));}
Back to Top

Construct genericprincipal and formsidentity objects

In this process, an Application Authentication event handler is implemented and constructed based on the information contained in the authentication ticket.GenericprincipalAndFormsidentityObject.

Construct genericprincipal and formsidentity objects

1.

Open global. asax from Solution Explorer.

2.

Switch to the Code view and add the following to the top of the file:UsingStatement:

Using system. Web. Security; using system. Security. Principal;

3.

FindApplication_authenticaterequestThe event handler and add the following code to obtain the form authentication cookie from the cookie set transmitted along with the request:

// Extract form authentication cookiestring cookiename = formsauthentication. formscookiename; httpcookie authcookie = context. Request. Cookies [cookiename]; If (null = authcookie) {// no authentication cookie. Return ;}

4.

Add the following code to extract the authentication ticket from the form authentication cookie and decrypt it:

Formsauthenticationticket authticket = NULL; try {authticket = formsauthentication. decrypt (authcookie. value);} catch (exception ex) {// record exception details (omitted for convenience) return;} If (null = authticket) {// The cookie cannot be decrypted. Return ;}

5.

Add the following code to parse the list of role names that are separated by pipe characters that are appended to a ticket after the user initially passes authentication:

// After creating a ticket, specify a role name string separated by pipe characters for the userdata attribute. String [] roles = authticket. userdata. Split (New char [] {'| '});

6.

Add the following code to create a ticket using the username obtained from the ticket nameFormsidentityObject, and create a list containing the identity and user rolesGenericprincipalObject:

// Create an ID object formsidentity id = new formsidentity (authticket); // the subject will pass the entire request. Genericprincipal principal = new genericprincipal (ID, roles); // attaches the new subject object to the current httpcontext object context. User = principal;
Back to Top

Test the application

This process adds code to the default. aspx page and displays the code appended to the currentHttpcontextObjectGenericprincipalObject, and make sure that the object has been correctly constructed and allocated to the current Web request. The application will be generated and tested.

Test the application

1.

In Solution Explorer, double-click default. aspx.

2.

Double-click the default. aspx web form to display the page loading event handler.

3.

Scroll to the top of the file, in the existingUsingStatement, add the followingUsingStatement:

Using system. Security. Principal;

4.

Return to the page to load the event handler and add the following code to displayGenericprincipalOn:

Iprincipal P = httpcontext. current. user; response. write ("authenticated identity:" + P. identity. name); response. write ("<p> ");

5.

Add the following code to test the role Member identity of the currently authenticated identity:

If (P. isinrole ("senior manager") response. write ("user in the senior manager role <p>"); else response. write ("the user is not in the senior manager role <p>"); If (P. isinrole ("manager") response. write ("user in the Manager role <p>"); else response. write ("the user is not in the Manager role <p>"); If (P. isinrole ("employee") response. write ("user in the employee role <p>"); else response. write ("the user is not in the employee role <p>"); If (P. isinrole ("sales") response. write ("user in sales role <p>"); else response. write ("the user is not in the sales role <p> ");

6.

In Solution Explorer, right-click default. aspx and click "set as start page ".

7.

On the "generate" menu, click "generate SOLUTION ". Exclude any compilation errors.

8.

PressCTRL + F5Run the application. Because default. aspx is configured as the start page, This is the page of the initial request.

9.

When you are redirected to the logon page (because you do not have an authentication ticket at first), enter the user name and password (you can enter anything), and then click "Log on ".

10.

Confirm that you are redirected to default. aspx, and the user ID and correct role details are displayed. The user should be a member of the Senior Manager, manager, and employee roles, rather than a member of the sales role.

Back to Top

Other resources

For more information, see the following chapters in this Guide:

How to use form authentication in Active Directory

How to use form authentication in SQL Server 2000


Back to Top

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.