Recently, I encountered a problem about how to perform identity authentication for Web Services exposed on the network, instead of being used by others. It took a day to read a book and I learned three methods, two of them are recorded below, and the other is Form verification. I cannot fully understand them, so I am not mistaken for them either. leave it blank and start:
Solution 1: Use the SOAP Header
First, we need to implement a class with authentication information, which inherits System. web. services. protocols. soapHeader, which defines two member variables: UserName and PassWord.
Public class MySoapHeader: SoapHeader
{
Public string UserName
{
Get;
Set;
}
Public string PassWord;
{
Get;
Set;
}
}
You can also add verification methods in this class. Of course, you need to look at the specific planning of your project.
Next is the Web Service writing method.
Code
Public class WebService: System. Web. Services. WebService
{
Public WebService ()
{
// If you use the designed component, uncomment the following line
// InitializeComponent ();
}
Public MySoapHeader header;
//// Define the header of the user authentication variable
[WebMethod (Description = "user verification test")]
[System. Web. Services. Protocols. SoapHeader ("header")] // soap header for User Authentication
Public string HelloWorld ()
{
String userName = header. UserName;
String passWord = header. PassWord;
Return "Hello World ";
// Add the method for permission verification. If there is already a method in the previous SOAPHeader, you can call it directly.
}
}
The code for client calls is relatively simple:
Code
Com. WebService test = new com. WebService (); // your web Service
MySoapHeader Header = new MySoapHeader (); // create a soap Header object using a web reference
// Set the soap header variable
Header. UserName = "Zane ";
Header. PassWord = "Yao ";
Test. MySoapHeaderValue = Header;
// Call the web method
Response. Write (test. HelloWorld ());
This completes ~
Solution 2: Set the web service program to integrated windows authentication. Of course, you must disable anonymous access,
Client web reference code
Test. WebReference. Service wr = new Test. WebReference. Service (); // generate a web service instance
Wr. Credentials = new NetworkCredential ("username", "password ");
Response. Write (wr. HelloWorld (); // call the web service Method