How to: Use Visual C # .NET in the ASP.NET application through a form-based authentication (from MSDN)

xiaoxiao2021-03-06  58

The release number of this article has been CHS311495

For Microsoft Visual Basic .NET versions of this article, see

306238.

This article references the following Microsoft .NET Framework Class Bank Name Space:

System.web.security system.security.principal

This task content

summary

Requires user roles that are verifying identity to check user roles in ASPX pages and implement program logic reference

SUMMARY This article describes how to realize role-based security in an ASP.NET application that implements form-based authentication by using Visual C # .NET.

Back to top

This article is assumed that you have implemented form-based authentication in the ASP.NET application.

306238 HOW TO: Using Visual Basic .NET implements role-based security in ASP.NET applications based on form-based authentication

Back to top

Assigning roles for authentication for authentication Because Form users are not Microsoft Windows users, there is no role associated with them by default. Therefore, the role of the user who performs authentication must be attached to the identity of the user to implement role-based security within the code.

Use the sample code in this section to achieve role-based security in your application. This sample code assigns a predetermined role to a user who performs authentication. Depending on your way you store user data, you can implement your own method to retrieve the role of authenticated users and attach these characters to the identity of the authentication user, the following code example shows this process.

Copy the following code to the global.asax file in the existing application, so that

Assign these characters to users who perform authentication in the Application_AuthenTicateRequest event handler:

Public void Application_AuthenticateRequest (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 top

Check the user role in the ASPX page and implement program logic The following steps demonstrate how to implement and control program logic depending on the role of the authentication user.

Newly built .aspx pages called Sample.aspx, then paste the following code: <% @ page language = "c #"%>

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