The process of building a forms-based authentication mechanism is as follows:
1. Set IIS to anonymous access and set form verification in Asp.net web. config.
2. retrieve the data storage to verify the user and retrieve the role (if not based on the role, do not use it)
3. Use formsauthenticationticket to create a cookie and send it back to the client.
The role is in the ticket, for example:
Formsauthentication. setauthcookie (username, true | false)
Cookie Retention Time:
Httpcontext. Current. response. Cookies [formsauthentication. formscookiename]. expires = datetime. Now. adddays (1)
If you need to store roles, use:
Formsauthenticationticket authticket = new
Formsauthenticationticket (
1, // version
Txtusername. Text, // User Name
Datetime. Now, // Creation
Datetime. Now. addminutes (20), // expiration
False, // persistent
Roles); // user data
Roles is a role string array.
String encryptedticket = formsauthentication. Encrypt (authticket); // Encryption
Store Cookie
Httpcookie authcookie =
New httpcookie (formsauthentication. formscookiename,
Encryptedticket );
Response. Cookies. Add (authcookie );
4. Process Program In the application_authenticaterequest event (Global. in asax), use the
ticket to create an iprincipal object with httpcontext.
Code in user:
httpcookie authcookie = context. request. cookies [formsauthentication. formscookiename];
formsauthenticationticket authticket = formsauthentication. decrypt (authcookie. value); // decrypt
string [] roles = authticket. userdata. split (New char [] {';'}); // It is decomposed according to the stored format; or | ....
context. user = new genericprincipal (context. user. identity, roles); // httpcontext exists. user
5. There are two ways to control roles on some pages:
5.1, add in Web. config
<Location Path = "editpost. aspx">
<System. Web>
<Authorization>
<Allow roles = "rolename"/>
<Deny users = "? "/>
</Authorization>
</System. Web>
</Location>
5.2 put files accessible only by some roles in the same directory, and add a web. config
<Configuration>
<System. Web>
<Authorization>
<Allow roles = "rolename"/>
<Deny users = "*"/>
</Authorization>
</System. Web>
</Configuration>