1 public class WebServiceAuthenticationModule : IHttpModule
2 {
3 private static WebServiceAuthenticationEventHandler
4 _eventHandler = null;
5 /// <summary>
6 /// 验证事件.绑定到此事件可进行对用户身份的识别
7 /// </summary>
8 public static event WebServiceAuthenticationEventHandler Authenticate
9 {
10 add { _eventHandler += value; }
11 remove { _eventHandler -= value; }
12 }
13 public Result Result = new Result();
14
15 public void Dispose()
16 {
17 }
18 public void Init(HttpApplication app)
19 {
20 app.AuthenticateRequest += new
21 EventHandler(this.OnEnter);
22 Result.EndValid += new
23 EventHandler(this.OnCheckError);
24 }
25
26 /// <summary>
27 /// 验证用户身份
28 /// </summary>
29 /// <param name=”e”></param>
30 private void OnAuthenticate(WebServiceAuthenticationEvent e)
31 {
32 if (_eventHandler == null)
33 return;
34
35 _eventHandler(this, e);
36 if (e.User != null)
37 e.Context.User = e.Principal;
38 }
39
40 public string ModuleName
41 {
42 get { return “WebServiceAuthentication“; }
43 }
44
45 void OnEnter(Object source, EventArgs eventArgs)
46 {
47 HttpApplication app = (HttpApplication)source;
48 HttpContext context = app.Context;
49 Stream HttpStream = context.Request.InputStream;
50
51 // Save the current position of stream.
52 long posStream = HttpStream.Position;
53
54 // If the request contains an HTTP_SOAPACTION
55 // header, look at this message.HTTP_SOAPACTION
56 if (context.Request.ServerVariables[“HTTP_SOAPACTION“] == null)
57 return;
58
59 // Load the body of the HTTP message
60 // into an XML document.
61 XmlDocument dom = new XmlDocument();
62 string soapUser;
63 string soapPassword;
64
65 try
66 {
67 dom.Load(HttpStream);
68
69 // Reset the stream position.
70 HttpStream.Position = posStream;
71
72 // Bind to the Authentication header.
73 soapUser =
74 dom.GetElementsByTagName(“User“).Item(0).InnerText;
75 soapPassword =
76 dom.GetElementsByTagName(“Password“).Item(0).InnerText;
77 }
78 catch (Exception e)
79 {
80 // Reset the position of stream.
81 HttpStream.Position = posStream;
82
83 // Throw a SOAP exception.
84 XmlQualifiedName name = new
85 XmlQualifiedName(“Load“);
86 SoapException soapException = new SoapException(
87 “SOAP请求没有包含必须的身份识别信息“, name, e);
88 throw soapException;
89 }
90 // 触发全局事件
91 OnAuthenticate(new WebServiceAuthenticationEvent
92 (context, soapUser, soapPassword));
93 Result.OnEndValid();
94 return;
95 }
96 void OnCheckError(Object sender, EventArgs e)
97 {
98 if (Result.BrokenRules.Count == 0)
99 {
100 return;
101 }
102 else
103 {
104 HttpApplication app = HttpContext.Current.ApplicationInstance;
105 app.CompleteRequest();
106 app.Context.Response.Write(Result.Error);
107 }
108 }
109 }
原文链接:https://www.cnblogs.com/Creator/archive/2011/03/23/1992019.html
原创文章,作者:优速盾-小U,如若转载,请注明出处:https://www.cdnb.net/bbs/archives/17245