In project development, we often use webservice, but when we use webservice we often consider the following questions: How to prevent people from accessing my webservice? Where do I cite my webservice? For the first question, WebService is a security issue, because the webservice we provide is not allowed to be quoted by all, and may only be used by the company or by authorized persons. So how to prevent illegal user access? It is easy to think of a set of user names and passwords to prevent illegal user calls.
A networkcredential is provided in System.Net, through which we can provide a credential in the network that only the user who obtains the credential can access the appropriate service. Here we also use the networkcredential. In NetworkCredential, we provide the name of the server where the WebService is published, and the user name and password (configured in IIS) to log on to the server and invoke the WebService.
Set its credential property when calling WebService, assign the credential credential above to it so that the WebService service is invoked only with the user name and password provided, and other users cannot access it. This will be sufficient to prevent WebService from being invoked by others.
As for the hostname, user name and password, for b/s can be configured by Webconfig, for C/s can use the application configuration file. This gives you the flexibility to configure.
The following is an example of C/s as a description, first we provide a server network credentials, and then through the WebRequest to verify the success of the connection. Of course, in order to save the user name and password, such as security, it can be encrypted and other means to ensure its security.
The following are the main source code:
/// <summary> ///Server Network Credentials/// </summary> /// <returns></returns> Public Staticnetworkcredential MyCred () {stringLoginuser = Properties.Settings.Default.UserName;//User name stringLOGINPSW = Properties.Settings.Default.UserPSW;//Password stringLoginhost = Properties.Settings.Default.HostName;//host name, which can be an IP address or server nameNetworkCredential myCred =NewNetworkCredential (LOGINUSER,LOGINPSW, loginhost); //networkcredential myCred = new NetworkCredential ("username", "123456", "Yourip");//"username", "123456", "YourServerName" returnmyCred; } /// <summary> ///Verify that the connection to the server is successful and returns true if the connection is successful/// </summary> /// <param name= "url" >Server WebService URL</param> /// <returns></returns> Public Static BOOLCredential (stringURL) { //Defining local Variables stringurl = g_url;//2009-02-25 Server Authentication only validated to machine Try { if(Mywebresponse = =NULL) {WebRequest mywebrequest= WebRequest.Create (URL);//Create a connection request based on a URLMywebrequest.credentials = MyCred ();//get the credentials for validation, which is the most important sentenceMywebrequest.timeout =20000;//Unit is millisecondsMywebresponse= Mywebrequest.getresponse ();//returns information when a connection succeeds } } Catch(WebException Wex)//Unable to connect to server, possibly due to server error or user name and password error { if(Mywebresponse! =NULL)//Destroy Pin{mywebresponse.close (); Mywebresponse=NULL; } return false; } Catch(Exception ex) {if(Mywebresponse! =NULL) {mywebresponse.close (); Mywebresponse=NULL; } return false; } finally { } return true; } Private StaticWs_webasic.ws_webasic Webasic =NULL;//Realizing Hua Ws_webasic.ws_webasic /// <summary> ///Ws_webasic Initialization/// </summary> Public Staticws_webasic.ws_webasic Ws_webasic {Get { if(Webasic = =NULL)//if the webasic is empty, it is re-instantiated, which reduces the time for validation and improves efficiency . { //webasic = new Zedi. Ws_webasic.ws_webasic (); //Wsbool = Credential (webasic. URL);//URL changed to server address 2009-02-25Wsbool =credential (G_url); if(Wsbool = =true)//Server Connection validation passed{webasic=NewWs_webasic.ws_webasic ();//instantiation ofWebasic. Credentials = MyCred ();//get the server connection credentials so that the WebService can safely connect } } returnWebasic; } }
Note:
(1) must quote System.Net;
(2) Access to WebService, remove anonymous access in IIS, if anonymous access is allowed, there is no need to provide authentication credentials. How to remove anonymous access in IIS please refer to the IIS related articles, which are not burdensome here.
Verification is sometimes slower, mainly because mywebresponse = Mywebrequest.getresponse ();
Two
Second, on the basis of the first method to encrypt the method in the webservice, there are many methods, the following provides a more common method. More than two parameters are provided when calling a method user encryption and decryption (of course, provide a few parameters to see their own needs). For example, there is a WebService method is to obtain the customer data in the database according to customer ID details of Getcustomerdetailbycustomerid (string CustID), if only one parameter is provided, it is easy to be accessed by others to call, So that the customer data is easily accessible to others, so we encrypt this method Getcustomerdetailbycustomerid (string scustid,string custid,ecustid); Only the two parameters of the correct scustid and Ecustid are provided to successfully invoke this method, and for these two parameters Scustid and Ecustid, a string can be generated by the encryption method, such as scustid= ' C39134558 ', ecustid= ' C39223525 ', only these two parameters meet certain conditions to verify the pass, and for the parameters, we can also provide a validation, if the value in Scustid C39134558, the front three bits must be C39, followed by 5 bit 13455 is added after the value 18 to perform bit operations such as, For a value of 18 plus a factor, such as 1, the following operation occurs: (18+1)%11==8, so that only the last one is 8 to calculate this parameter value is to meet the requirements, so casually input a parameter such as: C39134556, then because does not meet the requirements, so the validation can not pass. Here even if the two parameters scustid= ' C39134558 ', ecustid= ' C39223525 ' are all right, you also need to pass the further validation of these two parameters to be counted as successful. As for the two satisfying what requirements, one can use the existing encryption mechanism, you can also write a cryptographic class to socks. The above is just a simple example.
With the two steps above, you can implement a more secure webservice call.
Third, solution one: pass through the SOAP header authentication .
1. We implement a class for authentication, file name MySoapHeader.cs
The Mysoapheader class inherits from System.Web.Services.Protocols.SoapHeader. and defines two member variables, username and password, and defines a user-authenticated function Valideuser. It provides functionality for username and password checks
usingSystem;usingSystem.Data;usingSystem.Configuration;usingsystem.web;usingSystem.Web.Security;usingSystem.Web.UI;usingSystem.Web.UI.HtmlControls;usingSystem.Web.UI.WebControls;usingSystem.Web.UI.WebControls.WebParts;usingSystem.Web.Services;usingSystem.Web.Services.Protocols;/// <summary>///Summary description of Mysoapheader/// </summary> Public classmysoapheader:soapheader{ PublicMysoapheader () {// //TODO: Add constructor logic here// } Public stringUserName; Public stringPassWord; Public BOOLValideuser (stringIn_username,stringIn_password) { if(In_username = ="Zxq") && (In_password = ="123456")) { return true; } Else { return false; } }}
2. Below we create the Webservice.asmx WebService.cs code as follows:
usingSystem;usingSystem.Collections;usingsystem.web;usingSystem.Web.Services;usingSystem.Web.Services.Protocols;/// <summary>///Summary description of WebService/// </summary>[WebService (Namespace ="http://tempuri.org/")][webservicebinding (ConformsTo=wsiprofiles.basicprofile1_1)] Public classwebservice:system.web.services.webservice{ PublicWebService () {//If you are using a design component, uncomment the following line//InitializeComponent (); } PublicMysoapheader header;////define User authentication class variable header[WebMethod (Description ="User Verification Test")] [System.Web.Services.Protocols.SoapHeader ("Header")]//SOAP headers for user authentication Public stringHelloWorld (stringcontents) { //Verify that you have access to if(header.) Valideuser (header. UserName, header. PassWord)) {returnContents +"performed a"; } Else { return "you do not have permission to access"; } }}
3. Client creates a default.aspx
usingSystem;usingSystem.Configuration;usingSystem.Data;usingsystem.web;usingSystem.Web.Security;usingSystem.Web.UI;usingSystem.Web.UI.HtmlControls;usingSystem.Web.UI.WebControls;usingSystem.Web.UI.WebControls.WebParts; Public Partial class_default:system.web.ui.page {protected voidPage_Load (Objectsender, EventArgs e) {Com.cn1yw.WebService Test=NewCom.cn1yw.WebService ();//Web References (change to your own)Com.cn1yw.MySoapHeader Header =NewCom.cn1yw.MySoapHeader ();//Web References Create SOAP header objects (change to your own)//Set SOAP Header variablesHeader.username ="Zxq"; Header.password="123456"; Test. Mysoapheadervalue=Header; //Calling Web MethodsResponse.Write (Test. HelloWorld ("I am a strong")); }}
Solution two: Through Integrated Windows authentication.
1. Set the Web service program to Integrated Windows authentication
2. Client Web Reference Code
- Test.WebReference.Service1 WR = new Test.WebReference.Service1 (); Generate a Web service instance
- Url Credentials = new NetworkCredential ("Guest", "123"); Guest is the user name and the user needs to have certain permissions
- Lbltest.text = WR. ADD (2,2). ToString (); Calling the Web service method
The advantages of the scheme are relatively safe, good performance, the disadvantage is not easy to transplant, the deployment of large workload.
C # Authentication when invoking a Web service