Roles in forms validation

Source: Internet
Author: User
Tags object create index datetime httpcontext key string ticket access
The role of forms validation has been very vague, do not know how to do, last night carefully read the next CSDN magazine, a little bit at the bottom of the heart, this morning a csdn, see Shi adult back to a post, is about ASP.net forms validation roles, address is: http:// Www.codeproject.com/aspnet/formsroleauth.asp
Khan, how is e-wen, my e winter poor, but do not know why this unexpectedly was I understand, imitate his doing, unexpectedly success!, the special process and my understanding to write out, hope for and I like the rookie a little help, at the same time some of my understanding may be wrong, I hope you guys can point out, thank you very much, Below I begin to translate the side according to his doing:
1, first of all, we create a new database, called the Web, add a table called users, which has three fields, username field as the primary key, username and password fields set to the federated index, do not know that I understand this right? Please correct me.
CREATE
DATABASE Web

CREATE TABLE Users
(
Username nvarchar (CONSTRAINT) users_pk PRIMARY KEY,
Password nvarchar (128),
Roles nvarchar (64)
)

CREATE INDEX Credentials on users
(
Username
Password
)

We'll add two users to the Users table: Pwqzc 123456 Administrator,user
Pwq 123456 User
The first is the name, the second is the password, the third is the role that the user has, multiple roles, comma separated

2, create a landing page login.aspx
Put two textbox and a button inside, write code in the Click event of the button:
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 parameters 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 a database connection
Conn. Open ();
Execute 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,//Generate Cookie Time
DateTime.Now.AddMinutes (),//cookie effective time
false,//is not a permanent cookie
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 name of the cookie, the second parameter is the value of the cookie, which is the encrypted ticket.
HttpCookie cookie = new HttpCookie (formsauthentication.formscookiename,hashticket);
Setting a cookie is valid for a week
Cookie. Expires = DateTime.Now.AddDays (7);
Adding cookies to the response object occurs to the client
RESPONSE.COOKIES.ADD (cookie);
Get the requested URL
String requesturl = Formsauthentication.getredirecturl (Formsauthentication.formscookiename,false);
Do not use the FormsAuthentication.RedirectFromLoginPage method, because this method overrides the cookie
Redirect to the requested URL
Response.Redirect (Requesturl);
}
Else
{
If this user is not present, some errors are prompted
Errorlabel.text = "User name or password is wrong, please try again!";
Errorlabel.visible = true;
}
Turn off database connections and reader
Reader. Close ();
Conn. Close ();
}


3, the third step, in the application of the Global.asax, find Application_AuthenticateRequest, write the following code, remember to import using System.Security.Principal;
Using System.Web.Security; These two namespaces, the code is as follows:
protected void Application_AuthenticateRequest (Object Sender,eventargs e)
{
if (httpcontext.current.user!=null)//If user information exists in the current HTTP information
{
if (HttpContext.Current.User.Identity.IsAuthenticated)//If the current user's identity has passed the authentication
{
if (HttpContext.Current.User.Identity is formsidentity)
{
If the current user identity is the FormsIdentity class, the form validation class, this class has a property that can access the current user's verification ticket
FormsIdentity fi = (formsidentity) httpcontext.current.user.identity;//creates a formsidentity class that uses him to access the current user's verification ticket
Obtain the user's verification ticket
FormsAuthenticationTicket ticket = fi. Ticket;
Obtaining user data from the validation ticket, which is the role data
String userData = Ticket. UserData;
To decompose user data into an array of roles
string[] roles = Userdata.split (', ');
Rewriting the current user information to include the role information in the user's information
HttpContext.Current.User = new GenericPrincipal (fi,roles);
}
}
}
}

4, step fourth, modify Web.config
<configuration>
<system.web>
<authentication mode= "Forms" >
<forms name= "MyWebApp. Aspxauth "
Loginurl= "Login.aspx"
Protection= "All"
Path= "/"/>
</authentication>
<authorization>
<allow users= "*"/>
</authorization>
</system.web>
<location path= "admins" >
<system.web>
<authorization>
<!--order and case are important below-->
<allow roles= "Administrator"/>
<deny users= "*"/>
</authorization>
</system.web>
</location>
<location path= "Users" >
<system.web>
<authorization>
<!--order and case are important below-->
<allow roles= "User"/>
<deny users= "*"/>
</authorization>
</system.web>
</location>
</co



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.