Roles in Forms authentication

Source: Internet
Author: User

I have been very vague about the roles in forms verification, but I don't know how to do it. I carefully read the csdn magazine last night, and I have a little bit of heart. This morning I went to csdn, I can see a post back to the adults, is about the form authentication roles in Asp.net, the address is: http://www.codeproject.com/aspnet/formsroleauth.asp
Khan, how is it e-wen? My e-Wen is really poor, but I don't know why I understood it this time. It succeeded in imitating his work !, I want to write down the process and my understanding. I hope it will be helpful to cainiao like me. At the same time, some of my understandings may be incorrect. I hope you can point it out. Thank you very much, next I start to translate and follow his instructions:
1. First, create a new database named Web and add a table named users. There are three fields in the table. The username field is the primary key, and the username and password fields are set to the Union index, I don't know. Is that correct? Please correct
Create
Database Web

Create Table users
(
Username nvarchar (64) Constraint users_pk primary key,
Password nvarchiar (128 ),
Roles nvarchar (64)
)

Create index credentials on users
(
Username,
Password
)

We will add two users in the users table: pwqzc 123456 administrator and user
Pwq 123456 user
The first is the name, the second is the password, and the third is the user's role. Multiple roles are separated by commas (,).

2. Create a login page login. aspx
Put two textbox and a button in it, and write in the button clicking event Code :
Private void btnlogin_click (Object sender, system. eventargs E)
{
// Initialize formsauthentication
Formsauthentication. initialize ();
// Create a connection and command object
Sqlconnection conn = new sqlconnection ("Server = (local); uid = sa; Pwd = mydream54win; database = web ");
Sqlcommand cmd = conn. createcommand ();
Cmd. commandtext = "select roles from users where username = @ username and password = @ password ";
// Add and assign values to parameters
Cmd. Parameters. Add ("@ username", sqldbtype. varchar, 64 );
Cmd. Parameters ["@ username"]. value = username. value;
Cmd. Parameters. Add ("@ password", sqldbtype. varchar, 128 );
Cmd. Parameters ["@ password"]. value = password. value;
// Open the database connection
Conn. open ();
// Execute the command
Sqldatareader reader = cmd. executereader ();
If (reader. Read ())
{
// Create a new verification ticket formsauthenticationticket
Formsauthenticationticket ticket = new formsauthenticationticket (
1, // ticket version number
Username. Value, // cookie name
Datetime. Now, // cookie generation time
Datetime. Now. addminutes (30), // cookie Validity Period
False, // whether the cookie exists permanently
Reader. getstring (0); // User Role data read from the database
// Encrypt the verification ticket
String hashticket = formsauthentication. Encrypt (ticket );
// Set the verification ticket cookie. The first parameter is the cookie name, and the second parameter is the cookie value, that is, the encrypted ticket.
Httpcookie cookie = new httpcookie (formsauthentication. formscookiename, hashticket );
// Set the cookie validity period to one week
Cookie. expires = datetime. Now. adddays (7 );
// Adding the cookie to the response object occurs to the client
Response. Cookies. Add (cookie );
// Obtain the requested URL
String requesturl = formsauthentication. getredirecturl (formsauthentication. formscookiename, false );
// Do not use the formsauthentication. redirectfromloginpage method, because this method will overwrite the cookie
// Redirect to the requested URL
Response. Redirect (requesturl );
}
Else
{
// If this user does not exist, some errors are prompted.
Errorlabel. Text = "the user name or password is incorrect. Please try again! ";
Errorlabel. Visible = true;
}
// Close the database connection and Reader
Reader. Close ();
Conn. Close ();
}

3. Step 3: Program In global. asax, find application_authenticaterequest, write the following code, and remember to import using system. Security. Principal;
Using system. Web. Security; the two namespaces have the following code:
Protected void application_authenticaterequest (Object sender, eventargs E)
{
If (httpcontext. Current. User! = NULL) // if the current HTTP information contains user information
{
If (httpcontext. Current. User. Identity. isauthenticated) // if the identity of the current user has been verified
{
If (httpcontext. Current. User. Identity is formsidentity)
{
// If the current user identity is formsidentity, that is, Form Verification class, this class has an attribute that can access the verification ticket of the current user
Formsidentity Fi = (formsidentity) httpcontext. Current. User. Identity; // create a formsidentity class to access the verification ticket of the current user.
// Obtain the user's verification ticket
Formsauthenticationticket ticket = Fi. ticket;
// Obtain user data, that is, role data, from the verification ticket
String userdata = ticket. userdata;
// Use user data into a role Array
String [] roles = userdata. Split (',');
// Rewrite the current user information, that is, add the role information to the user information.
Httpcontext. Current. User = new genericprincipal (FI, roles );
}
}
}
}

4. Step 4: Modify the web. config



loginurl =" login. aspx "
Protection =" all "
Path ="/"/>























5. Test: create two directories admins and users under the application, and place default under their directories respectively. aspx: whatever is written above, set one of the default values. aspx settings ask start page (in vs2003 Environment). If you enter the name pwq and password, you cannot enter the admins directory, because this user does not belong to the administrator role!

Let's take a look at the basic principles of Forms authentication:
1. Authentication
To use forms authentication, you must first make the corresponding settings in Web. config in the application root directory.
Set:
<Authentication mode = "forms">
<Forms name = ". aspxauth" loginurl = "login. aspx" timeout = "30"
Path = "/"/>
</Authentication>
<Authentication mode = "forms"> indicates that the application uses forms validators.
.
<Forms> the name in the tag specifies the cookie to be used for identity authentication. The default value is. aspxauth. In fact, you can use any name, which is the first few words in the cookie you see on the local hard disk.
The authentication process of forms is as follows: 1. generate an authentication ticket; 2. encrypt the authentication ticket. 3. write back to the client. 4. Redirect the browser. in fact, this series of actions, if we don't use roles, all use formsauthentication. the redirectfromloginpage method completes this series of tasks. however, since we want to use roles authorization, we cannot use this method, but we need to separate it and complete it step by step.
First, create an authentication ticket. First, let's look at a constructor of the formsauthenticationticket class:
Public formsauthenticationticket (
Int version, // set to 1
String name, // user ID
Datetime issuedate, // cookie sending time, set to datetime. Now
Datetime expiration, // expiration time
Bool ispersistent, // whether it is persistent (set as needed. If it is set to persistent
Cookie expires must be set)
String userdata, // The role string prepared above that is separated by commas (,).
String cookiepath // is set to "/", which must be consistent with the cookie sending path, because the cookie is refreshed
Use this path
);
The last parameter can be omitted.
Formsauthenticationticket ticket = new formsauthenticationticket
(1, "Kent", datetime. Now, datetime. Now. addminutes (30), false, userroles)

Then encrypt:

String hashticket = formsauthentication. Encrypt (ticket );
// Set the verification ticket cookie. The first parameter is the cookie name, and the second parameter is the cookie value, that is, the encrypted ticket.
Httpcookie cookie = new httpcookie (formsauthentication. formscookiename, hashticket );
// Set the cookie validity period to one week
Cookie. expires = datetime. Now. adddays (7 );
// Adding the cookie to the response object occurs to the client
Response. Cookies. Add (cookie );
// Obtain the requested URL
String requesturl = formsauthentication. getredirecturl (formsauthentication. formscookiename, false );
// Do not use the formsauthentication. redirectfromloginpage method, because this method will overwrite the cookie
// Redirect to the requested URL
Response. Redirect (requesturl );

You can use httpcontext. Current. User. Identity. Name to identify the user on subsequent pages,
Httpcontext. Current. User. isinrole ("admin") determines whether a user belongs to a role (or a group)

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.