Implement an HTTP module that provides security services
Now we implement an HTTP module that provides security services for our Web applications. The HTTP module provides a customized identity authentication service. It will receive the identity credential in the HTTP request and determine whether the credential is valid. If valid, what are the user-related roles? The User. Identity object is used to associate these roles with the User IDs that access our Web application page.
The code of the HTTP module is as follows:
- Using System;
- Using System. Web;
- Using System. Security. Principal;
-
- Namespace SecurityModules
- {
- /// Overall description of Class1.
-
- Public class CustomAuthenticationModule: IHttpModule
- {
- Public CustomAuthenticationModule ()
- {
- }
- Public void Init (HttpApplication r_objApplication)
- {
- // Register the event handler with the Application object.
- R_objApplication.AuthenticateRequest + =
- New EventHandler (this. AuthenticateRequest );
- }
-
- Public void Dispose ()
- {
- // This field is empty because we do not need to perform any operations.
- }
-
- Private void AuthenticateRequest (object r_objSender, EventArgs r_objEventArgs)
- {
- // Identify the user's creden。 and find out the user role ..
- 1. HttpApplicationObjApp= (HttpApplication) r_objSender;
- 2. HttpContextObjContext= (HttpContext) objApp. Context;
- 3. if (objApp. Request ["userid"] = null) |
- 4. (objApp. Request ["password"] = null ))
- 5 .{
- 6. objContext. Response. Write ("<H1> Credentials not provided </H1> ");
- 7. objContext. Response. End ();
- 8 .}
-
- 9. stringUserid="";
- 10.Userid=ObjApp. Request ["userid"]. ToString ();
- 11. stringPassword="";
- 12.Password=ObjApp. Request ["password"]. ToString ();
- 13. string [] strRoles;
- 14.StrRoles=AuthenticateAndGetRoles(Userid, password );
- 15. if ((StrRoles= Null) | (strRoles. GetLength (0) = 0 ))
- 16 .{
- 17. objContext. Response. Write ("<H1> We are sorry but we cocould not
- Find this user id and password in our database </H1> ");
- 18. objApp. CompleteRequest ();
- 19 .}
-
- 20. GenericIdentityObjIdentity=NewGenericIdentity (userid,
- "CustomAuthentication ");
- 21.ObjContext. User=NewGenericPrincipal (objIdentity, strRoles );
- }
-
- Private string [] AuthenticateAndGetRoles (string r_strUserID, string r_strPassword)
- {
- String []StrRoles=Null;
- If (r_strUserID.Equals ("Steve") & (r_strPassword.Equals ("15 seconds ")))
- {
- StrRoles=NewString [1];
- StrRoles [0] = "Administrator ";
- }
- Else if (r_strUserID.Equals ("Mansoor") & (r_strPassword.Equals ("mas ")))
- {
- StrRoles=NewString [1];
- StrRoles [0] = "User ";
- }
- Return strRoles;
- }
- }
- }