Use WSE to implement Web Service Security (Web. config)

Source: Internet
Author: User
Tags asymmetric encryption
Use WSE to implement Web Service Security

WSe (Web Services enhancements) is a function enhancement plug-in launched by Microsoft to enable developers to create more powerful and useful web services through. net. The latest version is wse2.0 (SP2). This article describes how to use the security feature enhancement section in wse2.0 to implement secure Web Services. WSe security features are enhanced by the WS-Security Standard, which is the security protocol of WebService. It is jointly developed by IBM, Bea, Microsoft, and so on. net and Java systems.

I mainly write based on the WSE document description and my own experience (in fact, most of them are based on the document). If there are any errors, please point out. In addition, it uses 2.0, which is greatly changed compared with wse1.0, especially in terms of security.

Note that there are two ways to implement security through WSE: one is the method to write code which we will introduce below; the other method is to directly write a policy file (XML document). Both methods are based on the settings of the transmitted SOAP message, such as adding or decrypting user messages, to implement security functions. However, I am not familiar with the second method and have no time to study it.

 

1. Use the user name and password to verify the Web Services caller identity.

The principle is simple: the client uses soap extension to add the user name and password (plaintext or encrypted) to the SOAP message and send it to the Web Services end. After the server receives the message, you can also obtain the username and password from the message context through extension, and then perform authentication and other operations. The following are the implementation steps:

Client:

1. Add Microsoft. Web. Services2 and Web Services references to be accessed by the client. There is nothing to say. Of course, these two references are required. You may need to add other references to the client.

2. Modify the local proxy class generated by referencing Web services. The code of this class is in the reference generated reference file. Open the Web Services reference folder in Solution Explorer on the right of the. NET development environment, open the reference. Map node, and you will see the reference. CS or reference. VB file. If you do not see these files, it may not show all files. You need to set "show all files" in Solution Explorer or command menu "project ". Find the reference file, open it, and change the inherited parent class of the class to Microsoft in the proxy class declaration. web. services2.webservicesclientprotocol. only in this way can the proxy class access the soap extension provided by WSE. Note: If the Web service reference is updated, You need to modify the inheritance class again.

3. Add the user name and password through the instance of the userNameToken class. UserNameToken belongs to the Microsoft. Web. services2.security. tokens namespace. Assume that the local proxy class of Web Services is named webserver. WebService, the user name is username, and the user password is userpwd. The code can be as follows (VB.net, the same below ):

'Generate a local proxy instance

Dim mywebserv as new webserver. WebService

'Generate A userNameToken instance and write the username, user password, and password sending method in the instance.

Dim untoken as userNameToken = new userNameToken (username, userpwd, passwordoption. sendplaintext)

'Set the SOAP message validity period to reduce the possibility of re-use a message even if it is intercepted by another user. Here, it is set to 30 seconds, but pay attention to the clock synchronization problem between different systems.

Mywebserv. requestsoapcontext. Security. timestamp. ttlinseconds = 30

'Add the userNameToken instance to the context of the SOAP message

Mywebserv. requestsoapcontext. Security. tokens. Add (untoken)

'Webmethod

Mywebserv. webmethod

This describes how to set the password sending method. The sending methods of passwords are enumeration data: sendnone, sendhashed, and sendplaintext. The Hash Value of the sending password and the plaintext Text of the sending password are not sent respectively. The above example uses the sending plaintext. If sendnone is selected, it indicates that the server does not verify the password. This security level is very low. If the service needs to sign the passed SOAP message, the client must provide a separate password to sign it; sendhashed refers to sending the SHA-1 hash value of the password. In this case, the password is secure, which is also the best method recommended by Microsoft. However, the server needs to write code and configure the config file to authenticate the user's identity. The specific authentication method is described in the following server settings. sendplaintext is a password transmitted in plaintext, if this method is used, it is best to encrypt the userNameToken in the above Code, otherwise the password is easily intercepted. The encryption method will be discussed in detail later. In addition, if the server chooses to enable WSE to automatically perform authentication based on the users in the Windows Active Directory domain, you must select send plaintext here.

Server:

1. First, add the WSE configuration element to the Web. config configuration file of Web services. This is also the most basic step for the system developed by. Net to use WSE. In the WSE document, if the service calling end is an ASP. NET system, this configuration is required. If it is a common client program, this ID is not required. However, I found that this configuration still needs to be added even if the caller is a client program. The following is a complete configuration document.

<Configuration>

<System. Web>

<WebServices>

<Soapextensiontypes>

<Add type = "Microsoft. web. services2.webservicesextension, Microsoft. web. services2, version = 2.0.0.0, culture = neutral, publickeytoken = 31bf3856ad364e35 "priority =" 1 "group =" 0 "/>

</Soapextensiontypes>

</WebServices>

</System. Web>

</Configuration>

However, in general, you only need. <system. web>... </system. web> Add <WebServices>... </WebServices>. In addition, it is recommended that the data of the add element be written as one line, otherwise errors may occur.

2. This step is optional when configuring the authentication behavior of the server call.

As mentioned above, the user information has been added to the SOAP message sent by the caller. The server must parse the information, compare and verify the information according to certain rules, and return results.

The preceding processing process also has two options: one is to enable WSE to automatically verify, and our own code and configuration file no longer need to do anything. In this case, after receiving the SOAP message from the caller, WSE obtains the username and password from the userNameToken, this is also the reason why the user password must be sent in plain text under the automatic verification mentioned above. After the user name and password are obtained, WSE is used for identification and verification based on the user in the Windows domain where the system is located. That is to say, WSE traverses the user list in the Active Directory to find whether there is a valid user account that matches the received user name/password. If no matched user is found, then, an unauthorized caller error is returned. In this way, the application system and users need to be closely bound with the Windows domain, which lacks flexibility and is not suitable for interfacing with existing business systems. Therefore, the second method should be used in practical applications.

The core of this method is that Web Services is implemented by inheriting the usernametokenmanager class and reloading the authenticatetoken method.

A. first declare a class inherited from usernametokenmanager.

Public class customusernametokenmanager

Inherits usernametokenmanager

There is an access permission issue in this case. To enable the authorized assembly to access this class, you also need to add some access restrictions when declaring it. Because the trust level of the Assembly that can access the unmanagedcode is relatively high, it is required that the Assembly that can access this class can access the unmanagedcode. In this way, the above voice is changed to the following form:

<Securitypermission (securityaction. Demand, flags: = securitypermissionflag. unmanagedcode)> public class customusernametokenmanager

Inherits usernametokenmanager

Of course, you can configure Other permission requirements as long as you change the securitypermissionflag enumeration value of flags.

B. Reload the authenticatetoken method in the code. After the server receives a SOAP message containing the userNameToken instance, WSE deserializes the userNameToken and calls the verifytoken method. The verifytoken method calls the authenticatetoken method during execution, this method returns a password value, and WSE compares it with the password in userNameToken. If the password sent is plain text (userNameToken. passwordoption = sendplaintext), it is compared directly; if the sending password is a hash value (userNameToken. passwordoption = sendhashed), then WSE will perform a SHA-1 hash operation on the returned value, and then compare the result with the password in userNameToken. If they are inconsistent, an unauthorized user error is returned. The above process is completed automatically. Therefore, we need to reload the authenticatetoken method to return the correct user password for comparison and verification. This is actually equivalent to passwordprovider in wse1.0.

The logic for implementing the method of reload authenticatetoken is determined by the system according to specific requirements. For example, you can find the corresponding user password in the database based on the user name or in LDAP. As shown in the WSE document, the returned password is the same as the submitted username.

Protected overrides function authenticatetoken (byval username as userNameToken) as string

'Enable' that the soap message sender passed a userNameToken.

If username is nothing then

Throw new argumentnullexception

End if

'This is a very simple provider.

'In most production systems the following code

'Typically consults an external database of (username, hash)

'Pairs. For this example, it is the UTF-8

'Encodingof the user name.

Dim encodedusername as byte () = _

System. Text. encoding. utf8.getbytes (username. username)

Return System. Text. encoding. utf8.getstring (encodedusername)

End Function

C. Configure the Web. config file to inform web services of the class used to authenticate the user's identity.

First, add the element indicating the use of wse2 to the file:

<Configuration>

<Configsections>

<Section name = "Microsoft. Web. Services2"

Type = "Microsoft. Web. services2.configuration. webservicesconfiguration, Microsoft. Web. Services2, version = 2.0.0.0, culture = neutral, publickeytoken = 31bf3856ad364e35"/>

</Configsections>

</Configuration>

Note that <configsections>... </configsections> write the entire <configuration>... </configuration>. Otherwise, the error "text/html; charset = UTF-8" is returned, but it should be "text/XML.

Configure the usernametokenmanager subclass.

<Configuration>

<Microsoft. Web. Services2>

<Security>

<Securitytokenmanager xmlns: wsse = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" QNAME = "wsse: userNameToken" type = "mynamespace. example, myassemblyname, version = 2.0.0.0, culture = neutral, publickeytoken = example"/>

</Security>

</Microsoft. Web. Services2>

</Configuration>

Here, the value of the type attribute must be kept in one row. "mynamespace. customusernametokenprovider" must be a valid class level name for the derived class, and "myassemblyname" must be the Assembly name. In addition, attributes such as version, culture, and publickeytoken can be omitted.

In this way, we have completed the most basic user name/password-based authentication for Web service calls. In the future, security functions will be implemented based on it.

 

Ii. Sign a SOAP message using the user name and password

The above process implements web services user identity confirmation. However, it cannot ensure that the SOAP message received by Web Services is sent by the declared user. Therefore, in actual applications, the caller must sign the SOAP message, the signature is sent together with the message. After receiving the message, the server also needs to authenticate the signature. To confirm that the message has not been changed during transmission, and the verified user is the user who signed the message.

Client:

You only need to add a signature to the SOAP message of the original client, as shown in the following figure. The new Code is added to the blacklist:

Mywebserv. requestsoapcontext. Security. tokens. Add (untoken)

Mywebserv. Requestsoapcontext. Security. elements. Add (New _

Messagesignature (untoken ))

Mywebserv. webmethod

The above code is that the client generates a signature based on the userNameToken instance, and then adds the signature to the SOAP message, specifically the WS-Security extended SOAP message header.

Server:

The actual server does not need to be changed. As long as the SOAP message sent by the client contains a signature, the server automatically verifies the validity of the signature. The server first verifies the user name/password, and then uses the user name passed by the client and the password obtained by itself (WSE is automatically obtained from the Windows Active Directory, or through the overloaded authenticatetoken method) verify the signature. If the verification fails, the message is changed during transmission or is not signed by the currently called user, and an error is returned.

This section of the WSE help document adds a function to determine whether or not soap contains a signature. It is not necessary to obtain the signature information. If you are interested, you can check it yourself.

 

3. Use a certificate to authenticate the identity and sign the SOAP message

User Names/passwords have inherent drawbacks. Therefore, in some systems with strict security requirements, we also need to use certificates to authenticate user identities. The basic knowledge about PKI/CA is not introduced here. You can refer to the relevant materials.

First, we need to configure the server to ensure that WSe can access the certificate and its private key. (As for certificate application, management and use are basic knowledge, so I won't talk about it here.) Here, we mainly set it on the Web Services side to ensure that the server can automatically complete certain functions, user intervention is not required. Add the following <X509> element (simhei part) to the Web. config file ):

<Configuration>

<Microsoft. Web. Services2>

<Security>

<X509 storelocation = "currentuser"/>

</Security>

</Microsoft. Web. Services2>

</Configuration>

The storelocation attribute is the certificate storage that WSe can access. The optional values include "localmachine" and "currentuser", indicating the local certificate storage and the current user certificate storage respectively. Currentuser is used here, while storelocation defaults to localmachine. the other attributes are configured as follows: verifytrust: whether to verify the validity of the certificate chain used. The default value is true; allowtestroot: whether the certificate issued by the test Root CA is considered valid during the certificate chain process, this parameter is valid only when verifytrust is true. The default value is false. allowrevocationurlretrieval indicates whether the certificate is revoked online. It is valid only when verifytrust is true. The default value is true. allowurlretrieval, whether to verify the certificate chain validity online, allowrevocationurlretrieval, and whether to verify the certificate revocation status online.

 

Client:

Steps 1st and 2 are basically the same as steps for using the user name/password in section 1. But here we also need to add a reference: Microsoft. Web. services2.security. X509

3. Write the code to obtain the certificate to be used. I used a listview control to display the personal certificate in the current user certificate store for the user to choose. Of course, you can also use the certificate attributes as in the WSE document to locate the required certificate. The name of the listview control is lv_certlist, which has two columns: the name of the certificate holder and the issuer.

Dim Cert as x509certificate

Dim lvitem as listviewitem

'Open the personal certificate library from the current user certificate store

Certstore = x509certificatestore. currentuserstore (x509certificatestore. mystore)

Certstore. open ()

Lv_certlist.items.clear ()

'Print the certificate and write it to the listview control.

For each cert in certstore. Certificates

Lvitem = lv_certlist.items.add (CERT. getname)

Lvitem. subitems. Add (CERT. getissuername)

Lvitem. Tag = lvitem. Index

Next Cert

4. Select the selected certificate to generate the x509securitytoken instance, which is a subclass of securitytoken like the previous userNameToken.

Dim Cert as x509certificate

Dim certtoken as x509securitytoken

Dim result as string

CERT = certstore. Certificates (lv_certlist.selectedindices (0 ))

'Determine whether the selected Certificate supports signature and whether the private key exists

If cert. supportsdigitalsignature and not (CERT. Key is nothing) then

'Print the certificate and write it to the listview control.

Certtoken = new x509securitytoken (CERT)

Dim mywebserv as new webserver. WebService

Mywebserv. requestsoapcontext. Security. timestamp. ttlinseconds = 30

'Add the x509securitytoken containing the Certificate Information

Mywebserv. requestsoapcontext. Security. tokens. Add (certtoken)

'Sign the SOAP message using the certificate and write the result in the message

Mywebserv. requestsoapcontext. Security. elements. Add (New _

Messagesignature (certtoken ))

'Method of calling the Web Service

Mywebserv. webmethod

End if

 

Server:

Similar to the message used to sign the user name/password, the server automatically verifies the validity of the signature. In addition, the server verifies the certificate validity Based on the attribute settings in the <X509> element in the web. config file. If verification fails, an error is returned.

4. Use the user name and password to encrypt the SOAP message

As mentioned in section 1 above, if the password in the userNameToken instance is in plain text, it is best to encrypt and send the userNameToken. Make the following changes in the client code in section 1, and add the boldlike code:

Mywebserv. requestsoapcontext. Security. tokens. Add (untoken)

Mywebserv. Requestsoapcontext. Security. elements. Add (New _

Microsoft. Web. services2.security. encrypteddata (untoken ))

Mywebserv. webmethod

The above code is that the client encrypts the SOAP message according to the userNameToken, and then adds the ciphertext to the soap message, specifically the WS-Security extended SOAP message header.

The server automatically decrypts the message. The server first verifies the user name/password, and then decrypts the data using the user name passed by the client and the obtained password (WSE is automatically obtained from the Windows Active Directory, or through the overloaded authenticatetoken method. If it fails, an error is returned.

The WSE help document also adds a function to determine whether soap is encrypted.

 

5. Use Certificates to encrypt and decrypt soap messages

This is slightly more complex. According to the principle of PKI asymmetric encryption and decryption, the client that encrypts the message needs to obtain the certificate public key of the server that serves as the receiver in advance, and the server must ensure that the private key corresponding to the certificate can be accessed. Therefore, we must first set the certificate used by the server. The principle is to enable the server to automatically access the private key corresponding to the certificate at any time.

For Web Services developed based on ASP. NET, the default user must be granted the permission to access the private key of the certificate. The Default User of web services running on IIS 6.0 is network service. In other cases, the user account is owned by machine. the username attribute of the <processmodel> element in the config file is determined. If the parameter is missing, it is "machine", which is equivalent to the ASPNET account. To add a certificate, run the X.509 Certificate tool (--- program --- Microsoft WSE 2.0 --- X.509 Certificate tool) that comes with WSE 2.0, and select and open the certificate to be accessed by WSE. After the certificate is opened, the private key file name is displayed in the "private key file name" text box, and the private key file path is displayed in the "private key file name" text box. Click "private key file properties" to open the file Properties dialog box. You can add the authorized network service or ASPnet user account to the security properties page.

If the private key file does not exist or is inaccessible after the certificate is opened, the certificate is faulty or the private key is protected, for example, password-protected or stored in security peripherals, it cannot be automatically accessed by web services at any time, so it is not applicable.

For web services, if you are using the default ASPnet, you 'd better select the certificate in the Local Machine store. Because the ASPNET user is automatically generated when ASP. NET is installed, its password cannot be accessed. If the certificate is included in the current user store, the server may not be able to access the private key.

After the server sets the certificate, the client will obtain the certificate and public key. The specific method has something to do with your business system and application requirements. You can place it on the webpage for users to download and install it in advance. If the application is in a LAN environment, the client can be obtained in LDAP or Ca.

The client makes the following changes:

Mywebserv. requestsoapcontext. Security. tokens. Add (certtoken)

'Add encryption results to a SOAP message

 Mywebserv. requestsoapcontext. Security. elements. Add (New _

Microsoft. Web. services2.security. encrypteddata (certtoken ))

Mywebserv. webmethod

After the server receives the encrypted SOAP message, it automatically decrypts it using the corresponding private key. If it fails, an error is returned.

It can be seen that the difficulty in using certificates to encrypt and decrypt messages lies in the selection and configuration of certificates, especially the message receiving end.

 

In addition to the above username/password, WSE supports two tokens: X509 Certificate. It also supports kerberos ticket, security context token, and user-defined token. Kerberos ticket is like the content added by WSE. It is not included in the standard WS-Security, and is only supported on Windows XP SP1/SP2 and Windows2003. The security context token must be generated by a context token service. The core of a user-defined token is that securitytoken derives a user's own licensing class to complete various security functions. In short, WSE uses this token-based and extended SOAP message to implement web services security.

 

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.