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.