How to: Use Visual C # .NET to implement role-based security (from MSDN) in an ASP.NET application based on forms of forms.

xiaoxiao2021-03-06  59

This Article Was Previously Published Under Q311495

For a Microsoft Visual Basic .NET VERSION OF This Article, See

306238.

This Article Refers To The Following Microsoft .NET Framework Class Library Namespaces:

System.web.security system.security.principal

In this task

Summary

Requirements Assign The Roles To The Authenticating User Check The User Roles and Implement The Program Logic in Your ASPX Pages References

Summarythis article describes how to import role-based security in an asp.net application today implements forms-based Authentication Using Visual C # .NET

Back to the top

RequirementSthis Article Assumes That You Have Already Implement Forms-Based Authentication on an ASP.NET Application.

301240 How to Implement Forms-Based Authentication In Your ASP.NET Application Using C # .NET

Back to the top

Assign the Roles to the Authenticating UserBecause forms users usually are not Microsoft Windows users, they do not have any roles associated with them by default. Thus, you must attach the roles of the authenticating user to that user's identity so that you can implement the role -Based Security Inside your code.

Use the sample code in this section to implement role-based security in your application. This sample code assigns pre-specified roles to the authenticating user. Depending how you store your user data, you can implement your own method to retrieve the roles for that Authenticated User and attach those Roles to the Authenticating User's Identity, Which is illustrate in the sample code to follow.

Copy The Follow File in Your Existing Application To Assign The Roles To The Authenticating User In The Austrion

Application_AuthenTicateRequest Event Handler:

Public void Application_AuthenticateRerequest (Object Src, Eventargs E) {

IF (! (httpcontext.current.user == null))

{

IF (httpContext.current.user.Identity.AuthenticationType == "Forms")

{

System.web.security.formsidentity ID;

ID = (System.Web.Security.FormSidentity) httpContext.current.user.Identity;

String [] myroles = new string [2];

MYROLES [0] = "manager";

MYROLES [1] = "admin";

HttpContext.current.user = new system.security.principal.GenericPrincipal (ID, myroles);

}

}

}

Back to the top

Check the User Roles and Implement the Program Logic in Your .ASPX PagesThe following steps demonstrate how to implement and control the program logic based on the roles to which the authenticating user belongs.

Create a .aspx new page named sample.aspx, and paste the folload code: <% @ page language = "c #"%>

<% @ Import namespace = "system.web"%>