Recently, I am reading Asp.net forum, and I am very confused about the verification mechanism. After reading about how to build a secure ASP. NET applicationProgramIn the form authentication section, the idea is very clear, and a little record is made for reference:
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. In the application_authenticaterequest event processing program (Global. asax), use
The iprincipal object is created for the ticket and exists in httpcontext. User.
Code:
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); // In httpcontext. 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>
Note: The Web. config setting of sub-directories takes precedence over the web. config setting of the parent directory.
Here is a more comprehensive summary