Use HttpModule and forms authentication to control role Authentication

Source: Internet
Author: User
During this period, the project enters the end stage and remains idle. If it is okay, I will study some previously collected code and find ASP. NET is really powerful, just a web. config, I want to fully understand it, but I also need to spend some time. I just read HttpModule, made a small program, and wrote it down as my study notes.
HttpModules implements functions similar to ISAPI Filter. Generally, the following steps are required during development:
1. Write a class to implement the IhttpModule Interface
2. Implement the Init method and register the required Method
3. Registration Method
4. Implement the Dispose method. If you need to manually clear the class, you can add the implementation of the Dispose method, but this is not necessary. Generally, you can not add any code for the Dispose method.
5. register the written class in the Web. config file
There are already a lot of instructions on Forms authentication on the Internet. Next we will start this small role control program.
Create an asp.net project and add pages such as Login. aspx, Index1.aspx, index1.aspx, and default. aspx.
Add an xml file that stores user information, including the user name, password, and user role, as shown in the following code:
<UsersInfo>
<User name = "admin" password = "admin" role = "admin"/>
<User name = "user" password = "user" role = "user"/>
</UsersInfo>
In the system. web node in the web. config file, modify the authentication node according to the following code, set the authentication method to forms authentication, and set the login page
<Authentication mode = "Forms">
<Forms name = "TestAuth" loginUrl = "Login. aspx" protection = "None" timeout = "60"/>
</Authentication>
In addition, add the following node to control the user's access to the page as follows:
<Location path = "Index1.aspx">
<System. web>
<Authorization>
<Deny users = "? "Roles =" user "/>
</Authorization>
</System. web>
</Location>
Next in login. aspx. in cs, the click event processing function of the login button is added. Here we check whether the user name and password have been verified in the IsAuthenticated method, and obtain the roles information of the xml file after the verification, generate FormsAuthenticationTicket, save the roles information in userdata of ticket, add ticket to the cookie of the client, and redirect it to the page requested by the user.

Private void button#click (object sender, System. EventArgs e)
{
If (this. IsAuthenticated (TextBox1.Text, TextBox2.Text ))
{
String userId = TextBox1.Text;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1, userId, DateTime. Now, DateTime. Now. AddSeconds (30), false, roles );
HttpCookie cookie = new HttpCookie (FormsAuthentication. FormsCookieName, FormsAuthentication. Encrypt (ticket ));
Response. Cookies. Add (cookie );
Response. Redirect (FormsAuthentication. GetRedirectUrl (userId, false), true );
}
}

Add a new class in the project, inherit the IHttpModule interface, implement the Init method, and register the required method:

Namespace WebApplication1
{
/** // <Summary>
/// Summary description for AuthenticationModule.
/// </Summary>
Public class AuthenticationModule: IHttpModule
{
Public AuthenticationModule ()
{
//
// TODO: Add constructor logic here
//
}

Private void Authentication_Request (object sender, EventArgs e)
{
HttpApplication App = (HttpApplication) sender;
HttpContext Ctx = App. Context;
If (Ctx. Request. IsAuthenticated = true)
{
FormsIdentity Id = (FormsIdentity) Ctx. User. Identity;
FormsAuthenticationTicket Ticket = Id. Ticket;
String [] Roles = Ticket. UserData. Split (',');
Ctx. User = new GenericPrincipal (Id, Roles );
}
}

IHttpModule Members # region IHttpModule Members

Void IHttpModule. Init (HttpApplication context)
{
Context. AuthenticateRequest + = new EventHandler (this. Authentication_Request );
}

Void IHttpModule. Dispose ()
{
}

# Endregion
}

}

In the above Authentication_Request method, create a FormsIdentity object and a GenericPrincipal object. The previous object obtains the user name from the ticket name, and the latter object includes this identity with the user role list.
Finally, register the AuthenticationModule class you just compiled in web. config, and add the following code under the system. web node that just modified the authentication method:
<HttpModules>
<Add name = "AuthenticationModule" type = "WebApplication1.AuthenticationModule, WebApplication1"/>
</HttpModules>
After compilation, you can set index1.aspx as the start page and run it. Is it redirected to the login. aspx page? Then, log in with the user and admin respectively to see the effect.
Conclusion: if you do not need httpModule, you can add the content in the Authenticate_Requset method to global. asax. in the cs file Application_AuthenticateRequest method, the effect is the same, but here I have a small question, I have found many articles on the Internet in global. asax. cs's Application_AuthorizeRequest method processes the code just now. I have tried it. It must be placed in Application_AuthenticateRequest, because Application_AuthenticateRequest runs before Application_AuthorizeRequest. I hope you can give me some advice, did I make a mistake or did I make a mistake on the Internet?

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.