Several implementation methods of WebService security "identity recognition"

Source: Internet
Author: User
Tags httpcontext soap

ext.: http://blog.csdn.net/yongping8204/article/details/8619577Several implementation methods of WebService security "identity recognition"Tags: WebService safety certification2013-02-27 21:51 7778 People read comments (0) favorite reports Classification:Web Technology (C #)

I believe that many developers have used webservice to implement the program's service-oriented, this article mainly introduces the webservice of identity recognition implementation, of course, this article will provide a not very perfect example, right when the brick lead jade.

First, let's introduce two kinds of verification methods under WebService,

I. Integration with Windows authentication

By integrating Windows to solve WebService security issues is a very concise, and effective solution, the advantages of the scheme is relatively safe, good performance, of course, because with Windows tightly together, the shortcomings are naturally obvious, first, not easy to transplant, second, To make the relevant configuration deployment work (of course, we can also use code to operate IIS, but it is more troublesome, recently has been doing automated deployment, so the configuration will immediately associate with how to automatically deploy)

How do you do it specifically?

Server-side: Configure IIS Virtual directories for Integrated Windows authentication

Client:

Service1 WR = new Service1 (); Web Service Instance

Url Credentials = new NetworkCredential ("Administrator", "123"); User name password

Lbltest.text = WR. ADD (2,2). ToString (); Call the Add Web service method

Two. Using SoapHeader (SOAP header) to customize the authentication

SoapHeader most of the circumstances used to pass the user authentication information, of course, its role is far more than that, to be explored in the actual application, the body can achieve what things people have ideas to communicate with the message.

SoapHeader Steps to use:
(1) Create a custom SoapHeader type that inherits from System.Web.WebServices.SoapHeader.
(2) Create a custom soapheader field in WebService that has public access.
(3) Add the Soapheaderattribute Access feature on WebMethod that need to use SoapHeader. The Soapheaderattribute construct must specify the MemberName parameter, which is the name of the field we declared in the second step.
(4) The generator automatically generates custom SoapHeader types for the client with the same name, but is more complex than what we created on the WebService side. A Soapheadervalue property is also added for the proxy type.

The following shows a SoapHeader code, and the extra method will be used later

Client

Class program    {        static void Main (string[] args)        {            Service1 ws = new Service1 ();            Servicecredential mycredential = new Servicecredential ();            Mycredential. User = "Gazi";            Mycredential. Password= "Gazi";            Ws. Servicecredentialvalue = mycredential;            String  mystr=ws. SayHello ();                    }    }

Server-side

 public class Service1:System.Web.Services.WebService {public servicecredential mycredential;        [WebMethod] [SoapHeader ("mycredential", Direction = soapheaderdirection.in)] public string SayHello () {RE        Turn "Hello";        }}public class Servicecredential:soapheader {public string User;        public string Password;        public static bool Valideuser (string user,string Password) {return true; The public static void CheckUser (Object sender, Webserviceauthenticationevent e) {if (Valideuser (E .            User, E.password)) {return; } else {Webserviceauthenticationmodule module = sender as Webserviceauthenticationmo                Dule; Module.            Result.addrule ("Validation error", "Cannot confirm your identity, please check user name and password"); }        }    }

When we have a lot of classes, it is very troublesome to add one or delete a verification method (assuming that multiple certifications are required), and it is not possible to run into each method to add a method call, which is disastrous, and of course we can do it with AOP. AOP words need to add a lot of code or directly into a third party to do, but can we have a simpler way?

OK, the answer is to use HttpModule, we integrate IHttpModule write a processing module, then what is the principle of it? What are the specific operations? Our ideas are as follows:

    1. The HTTP Module parses the HTTP message to check that they are not SOAP messages.
    2. If the HTTP Module detects a SOAP message, it reads the SOAP header.
    3. If there is authentication credentials in the SOAP header of the SOAP message, the HTTP Module throws a custom Global.asax event.

Take a look at our module code below

  1 public class Webserviceauthenticationmodule:ihttpmodule 2 {3 private static webserviceauthentication  EventHandler 4 _eventhandler = null; 5//<summary> 6///authentication event. Bind to this event to identify user identity 7//</summary> 8 public Stat             IC Event Webserviceauthenticationeventhandler Authenticate 9 {add {_eventhandler = value;} 11 Remove {_eventhandler-= value;} The public result result = new result ();         public void Dispose () () () ()-{19} public void Init (HttpApplication app. {app. AuthenticateRequest = new EventHandler (this. OnEnter); Result.endvalid = new EventHandler (this. ONCHECKERROR); +/-<summary> 27//Authentication User ID//</summary>//<p Aram Name= "E" ></param> private void OnAuthenticate (Webserviceauthenticationevent e) (_eventhandler = = null) return; _eventhandler (this, e); if (e.user! = null) PNs E.context.user = E.principal; A. "ModuleName" ("Webserviceauthentication")  } OnEnter (Object source, EventArgs EventArgs). {HttpApplication App = (HttpApplication) source; HttpContext context = App. Context; The Stream Httpstream = context. Request.inputstream; //Save The current position of stream. Posstream long = httpstream.position; Contains//If the request is http_soapaction//header, look at this message. Http_soapaction if (context.  request.servervariables["http_soapaction"] = = null) 57               Return +//Load the body of the HTTP message #/to an XML document. XmlDocument dom = new XmlDocument (); Soapuser string; Soappassword string; Up to a try, and then the DOM. Load (Httpstream); Position//Reset the stream. Httpstream.position = Posstream; //Bind to the authentication header. Soapuser = the DOM. getElementsByTagName ("User"). Item (0). InnerText; Soappassword = the DOM. getElementsByTagName ("Password"). Item (0). InnerText; (Exception e) +//Reset the position of stream. 8 1 httpstream.position = Posstream; Exception//Throw a SOAP.                        XmlQualifiedName name = new 85      XmlQualifiedName ("Load"); SoapException SoapException = new SoapException (the "SOAP request does not contain the required identifying information", NA Me, E); SoapException throw;                          89} 90//Trigger global event OnAuthenticate (new Webserviceauthenticationevent 92 (Context, Soapuser, Soappassword)); Result.onendvalid (); 94 return; The Oncheckerror (Object sender, EventArgs e), {98 if (RESULT.BROKENRULES.C                 Ount = = 0) return;101}102 else103 {104 HttpApplication app = httpcontext.current.applicationinstance;105 app. CompleteRequest (); 106 app. Context.Response.Write (result.error); 107}108}109}

The authenticate event is a static variable so that we can subscribe to and unsubscribe from events outside of the program (non-static public events are also not allowed to subscribe and unsubscribe events externally, which is one of the differences between events and delegates)

Here are our event parameters and the delegate

 1 public delegate void Webserviceauthenticationeventhandler (Object sender, webserviceauthenticationevent e);  2 3//<summary> 4//Package Event Parameters 5//</summary> 6 public class Webserviceauthenticationevent : EventArgs 7 {8 private IPrincipal _iprincipaluser; 9 private HttpContext _context;10 Priva Te string _user;11 private string _password;12 public webserviceauthenticationevent (HttpContext context ) {_context = context;16}17 public webserviceauthenticationevent (HttpContext             context,19 string user, string password) {_context = context;22             _user = user;23 _password = password;24}25 public HttpContext Context26 {27 get {return _context;} }29 public IPrincipal Principal30 {get {return _iprincipaluser;} Set {_iprincipaluser = value;} }34 public void Authenticate () {GenericIdentity i = new GenericIdentity (User); PNS this.         Principal = new GenericPrincipal (i, new string[0]);}39 public void Authenticate (string[] roles) 40 {GenericIdentity i = new GenericIdentity (User); Principal = new GenericPrincipal (i, roles);}44 public string User45 {$ get {retur n _user; }47 set {_user = value;} }49 public string Password50 {---get {return _password;} set {_password = value;} }54 public bool HasCredentials55 {get57 (_us ER = = null) | | (_password = = null)) false;60 return true;61}62}63}

In the Application_Start method of Global.asax, we servicecredential.checkuser subscribe the static method described earlier to our authenticate event, The addition and deletion of multiple authentication methods mentioned earlier is achieved through this approach.

  protectedvoidapplication_start(object sender,EventArgs e){  Webserviceauthenticationmodule.  Authenticate+ =servicecredential.  CheckUser;}                 

We set the Servicecredential.valideuser method to return False, which is a configuration for the test, in fact we can combine with the database to write a certification run the code that explains SoapHeader, You will find that our certifications are already in effect. About the result class used in the article a day in a paper, this is a very good way to record the wrong scenario

Several implementation methods of WebService security "identity recognition"

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.