ASP. NET forms-based authentication mechanism-Role authorization

Source: Internet
Author: User
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)

Simple role-free mode:

Use formsauthenticationticket to create a cookie and send it back to the client, and store the role in the ticket, for example:
Formsauthentication. setauthcookie (username, true | false)
Cookie Retention Time:
Httpcontext. Current. response. Cookies [formsauthentication. formscookiename]. expires = datetime. Now. adddays (1)

To store roles:

  1. Formsauthenticationticket authticket =New
  2. Formsauthenticationticket (
  3. 1,// Version
  4. Txtusername. Text,// User Name
  5. Datetime. Now,// Creation
  6. Datetime. Now. addminutes (20 ),// Expiration
  7.  False,// Persistent
  8. Roles );// User data
  9. // Roles is a role String Array
  10.  StringEncryptedticket = formsauthentication. Encrypt (authticket );// Encryption
 
Formsauthenticationticket authticket = newformsauthenticationticket (1, // versiontxtusername. text, // user namedatetime. now, // creationdatetime. now. addminutes (20), // expirationfalse, // persistentroles); // user data // roles is a role String Array string encryptedticket = formsauthentication. encrypt (authticket); // Encryption

Store Cookie

    1. Httpcookie authcookie =
    2. NewHttpcookie (formsauthentication. formscookiename,
    3. Encryptedticket );
    4. Response. Cookies. Add (authcookie );
 
Httpcookie authcookie = new httpcookie (formsauthentication. formscookiename, encryptedticket); response. Cookies. Add (authcookie );

Process in application_authenticaterequest eventProgramIn (Global. asax), use the ticket to create the iprincipal object and the object exists in httpcontext. User.Code:

  1. Protected VoidApplication_authorizerequest (ObjectSender, system. eventargs E)
  2. {
  3. Httpapplication APP = (httpapplication) sender;
  4. Httpcontext CTX = app. context;// Obtain the httpcontext object related to this HTTP Request
  5.  If(CTX. Request. isauthenticated =True)// A verified user can process the role.
  6. {
  7. Formsidentity id = (formsidentity) CTX. User. identity;
  8. Formsauthenticationticket ticket = ID. ticket;// Obtain the authentication ticket
  9.  String[] Roles = ticket. userdata. Split (',');// Convert the role data in the authentication ticket to a String Array
  10. CTX. User =NewGenericprincipal (ID, roles );// Add the original identity with the role information to create a genericprincipal to indicate the current user, so that the current user has the role information
  11. }
  12. }
 
Protected voidPostauthenticaterequest(Object sender, eventargs E)
{Httpapplication APP = (httpapplication) sender; httpcontext CTX = app. context; // obtain the httpcontext object related to this HTTP request if (CTX. request. isauthenticated = true) // The authenticated user performs role processing {formsidentity id = (formsidentity) CTX. user. identity; formsauthenticationticket ticket = ID. ticket; // get the authentication ticket string [] roles = ticket. userdata. split (','); // convert the role data in the authentication ticket to a string array CTX. user = new genericprincipal (ID, roles); // Add the original identity with the role information to create a genericprincipal to indicate the current user, so that the current user has the role information }}

There are two ways to control roles on some pages:
1. Add in Web. config

    1. "editpost. aspx " >
    2. "rolename" />
    3. "? " />
<Location Path = "editpost. aspx"> <system. Web> <authorization> <allow roles = "rolename"/> <deny users = "? "/> </Authorization> </system. Web> </location>

2. Place files accessible only by some roles in the same directory and add a web. config

    1. "rolename" />
    2. "*" />
<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.

Forms authentication, Why can't all users enter after <allow roles = "Administrators"/> <deny users = "*"/>?

It is wrong to put the authorization code in application_authorizerequest! Due to many problemsArticleThey are all references, so it is very good for programmers to be killed. They should be put in the following event.

Void application_postauthenticaterequest (Object sender, eventargs E)
{
Httpapplication APP = (httpapplication) sender;
Httpcontext CTX = app. Context; // obtain the httpcontext object related to this HTTP Request
If (CTX. Request. isauthenticated) // The authenticated user can process the role.
{
Formsidentity id = CTX. User. Identity as formsidentity;
Formsauthenticationticket ticket = ID. Ticket; // get the authentication ticket
String [] roles = ticket. userdata. Split (','); // convert the role data in the ticket to a String Array
CTX. user = new system. security. principal. genericprincipal (ID, roles); // Add the original identity with the role information to create a genericprincipal to indicate the current user, so that the current user has the role information
}
}


Please refer to: http://community.csdn.net/Expert/TopicView3.asp? Id = 5526963

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.