Formsauthentication authentication with role information

Source: Internet
Author: User

Steps:

1. manually set formsauthenticationticket upon logon. The Code is as follows:

// You can manually add formsauthenticationticket
Formsauthenticationticket ticket = new formsauthenticationticket (1, "username", datetime. Now, datetime. Now. addminutes (20), false, "admin ");
// Encryption
String hashticket = formsauthentication. Encrypt (ticket );
// Generate cookie
Httpcookie usercookie = new httpcookie (formsauthentication. formscookiename, hashticket );
// The cookie of the authentication ticket is output to the client
Response. Cookies. Add (usercookie );

2. Add the following code to global:

     protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
//Construst the GeneralPrincipal and FormsIdentity objects
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];

if (null == authCookie)
{
//no authentication cokie present
return;
}

FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

if (null == authTicket)
{
//could not decrypt cookie
return;
}

//get the role
string[] role = authTicket.UserData.Split(new char[] { ',' });
FormsIdentity id = new FormsIdentity(authTicket);

Context.User = new GenericPrincipal(id, role);
}

In this way, we can use [authorize (roles = "admin")] in the program for verification.

Related Article

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.