J2EE Web Service Development Series 12: Security Axis Web Services, Part 1

xiaoxiao2021-03-06  55

Axis is a popular web service development tool, how to develop secure web services in AXIS, which is a problem in front of each developer. This article is the 12th article of J2EE Web Service Development Series, will first briefly introduce the basic concept of Web service security, then introduce some common methods for handling security issues under the AXIS web service development tool; next to security implementation For the clues, how to configure access control for web services on the web application, how to use the AXIS's Handler and Servlet filters to access control, and finally discuss how to configure SSL under Tomcat to implement the security transmission of Web services. This article will introduce how to implement WS-Security in AXIS.

You need the following knowledge and tools before reading this article:

Apache axis1.1, will be used initially; Tomcat 4.0 or more, and will preliminate; servlet development experience; SOAP Message programming knowledge; JAX-RPC programming basics; Java security programming basics.

The reference materials of this article are found.

All code in this article is downloaded here.

Web Service Security Overview Security Web Services is the necessary guarantee for the success of web services. However, it is well known that the web service uses XML to perform data exchange, and XML is clearly encoded by default; at the same time, most Web services use HTTP protocols as transport protocols, and HTTP is also used to transmit data using clear text. This causes the information transmitted to transmit non-encrypted information to threatens the confidentiality of information transmission on the transfer protocol that is not encrypted. As an enterprise-class application, the above ways cannot meet the basic requirements of safety:

Data should not be seen by a third party when spread on the Internet; the two sides must be able to determine the source of the message; the two sides must be able to determine that the transmitted data is not tampered.

The first problem can be solved by using the SSL protocol: "Should not be seen by a third party"; use digital signatures and digital certificates to solve two problems. When using a digital certificate method, the Web service request must have a digital certificate signed by the Trusted Certification Center. The requester uses this certificate to indicate their identity and digitally sign the SOAP message. After receiving the message for the other party, the message can be timestamp and log record. At this point, the digital signature will be verified. The verification process will ensure that the message comes from the sender and also verifies that the message content is not tampered with during transmission.

IBM, Microsoft and Verisign jointly issued a specification of Web Services Security (WS-Security) in December 2002, which describes how to attach a signature and encrypted header to the SOAP message; in addition, it also describes How to attach a security token (including binary security tokens, such as X.509 certificates), provide a mechanism for helping Web service developers protect SOAP messaging.

Depending on the level of security requirements, different ways can be implemented in different ways, the following is some of the most common implementations (from low to high alignment):

J2EE web application default access control (data is clear); use AXIS's Handler to access control (data is clear); use the servlet filter (Filter) to access control (data is clear); use SSL / HTTPS protocol To transmit (encrypted data transfer protocol); encrypt information using the WS-Security specification (data encrypted transmission). The first three ways are feasible for applications with high security levels, which can use web application access authentication mechanisms to verify permission, so that access to resources is protected. However, it should be noted that although they perform authentication, the delivery of information is carried out in a clear manner, and cannot guarantee that the information is not stolen during transmission. SSL is a secure transmission protocol that uses it to transmit web services to ensure that information is not stealing by a third party. But it has a disadvantage that the system resource consumption is large. With the last way, the information is signed and then encrypted, and then transmits the encrypted information network, so that even if the third party obtains the encrypted transmission information, it cannot be decrypted. For systems with high security levels, WS-Security specification should be used as a Web service security solution.

Development, deployment example web services As an exemplary tutorial, we must first develop a simple web service as an example. About how to develop and deploy a simple web service under AXIS You can refer to the following article: Develop Web services with JAX-RPC: servlet as a web service endpoint.

The following example provides a Web service that provides personal income tax calculations. The amount of the client is incompatient, and the Web service will calculate the personal income tax amount.

Routine 1 personal income tax web service

Package com.hellking.study.webservice;

Public Class PersonalTaxService

{

Final Double Base = 1200; // Called the base.

Public Double GetTax (Double Salry)

{

Double Tax_salary = SALARY-1200;

Double TAX = 0.0d; // The income tax after calculation.

IF (0> TAX_SALARY) TAX = 0;

Else IF (0

Else IF (500

...

Return Tax;

}

}

After compiling, you can add the following deployment code in the appropriate location of the deployment profile (Axis_home / web-inf / server-config.wsdd), the web service can be deployed.

Routine 2 Deployment Sample Web Services

The Web service URL after deployment is: http: // localhost: 8080 / axis / services / personaltaxservice? WSDL (please deploy this web service and make the following learning.)

From the basic authentication from the web application, regardless of the client through what API to call the web service, it always constructs the SOAP message, then send the message to the web service through the HTTP POST method (Note 1: Of course, the web service can also Through other text-based protocols, due to very rare, it will not be discussed here). And we know, regardless of the deployment of AXIS (Tomat or WebSphere), it always runs in servlet. So the simplest way to implement Web service is to achieve access control by profile (web.xml) in the web application.

There are a variety of authentication methods in the J2EE web application: BASIC (Basic Authentication Method), Form (Based on Form), Digest (Message Summary) and Client-Cert (Digital Certificate). For other information on other authentication methods for J2EE web applications, refer to other information, which is not described here.

Below Tomcat uses servers as an example, the basic authentication method in the web application model is used to configure security access to Web services.

The basic authentication of the web application is based on the J2EE role and the user, first adding a role and an account in the Tomcat role profile.

Routines 3 Add Roles in Tomcat-Users.xml (Tomcat_Home / conf / Tomcat-users.xml)

...

...

The above configuration code adds a department-manager role in the Tomcat configuration file, and adds a user named Hellking in this role. To make the roles and users configured in Tomcat-Users.xml, you need to configure Tomcat to use USERDATABASEREALM. Open tomcat_home / conf / server.xml configuration file, add the following description in GlobalNamingResources:

Routines 4 Add UserDatabaseRealm in Tomcat

...

Type = "org.apache.catalina.userdatabase"

Description = "User Database That Can Be Updated and Saved">

factory org.apache.catalina.users.MemoryUserDatabaseFactory

pathname

conf / tomcat-users.xml

Then specify the access control of the web service resource in the deployment descriptor of the Web application, as shown below:

Routine 5 Configure Access Control for Servlet (Axis_Home / Web-INF / Web.xml)

TAX Web Service

/ services / personaltaxservice

Department-manager

Basic

Axis Basic Authentication Area

Department-manager

URL-Pattern specifies the URL style that needs to be verified by role, here is "/ services / personaltaxservice"; role-name is a role that can access the developed URL, here is Department-Manager. The above configuration means that only the role type is "department-manager" users to access the URL style to "/ Services / PersonalTAXService" web service.

Here we see how to AXIS client in the AXIS client code, as shown in routine 6.

Routine 6 AXIS client code

Package com.hellking.study.webservice;

Import org.apache.axis.client.call;

Import org.apache.axis.client.service;

. . .

/ **

* WEB services that need to be verified

* /

Public Class AuthClient

{

Static Final Double Salary = 5000;

Public static void main (string [] args)

{

Try {

// The server's URL needs to be changed according to the situation.

String endpointURL = "http: // localhost: 8080 / axis / services / personaltaxservice? WSDL"; //

// Web service endpoint address service service = new service ();

Call call = (call) service.createcall ();

Call.settargetendpointaddress (New Java.net.URL (EndpointURL);

Call.SetoperationName (New QName ("PersonalTaxService", "getTax")); // Set the name of the operation.

// If you need to authenticate, you need to set the username and password.

Call.getMessageContext (). setusername ("Hellking"); // Set the username.

Call.getMessageContext (). setPassword ("SimpleWebServices"); // Set password

Call.addparameter ("OP1", XMLTYPE.XSD_DOUBLE, ParameterMode.in; // Parameter Type

Call.setRetURNTYPE (XMLTYPE.XSD_DOUBLE); // Returned Data Type

Double Ret = (Double) Call.invoke (New Object [] {new double (salary)}); // Execute call

System.out.Println ("Use the HTTP protocol to use the transfer protocol of the web service!");

System.out.println ("has been called successfully. Please refer to the output of the server!");

System.out.println ("Enter the wage" Salary ", pay personal income tax:" RET);

. . .

}

}

It can be seen that the calling user name is set by using call.getMessageContext (). SetUsername ("Hellking"), set the calling password by setpassword. It can be seen from the above code that other code and no access control are not used in addition to the username and password set for the CALL object.

Let's take a look at its results:

Use the HTTP protocol as a transfer protocol for web services!

Has been successfully called. See the output of the server!

Enter the salary of 5,000.0 yuan, you should pay personal income tax: 445.0

As can be seen from the output, the client successfully passed the verification and returned the correct result.

Access Control AXIS's Handler for access control AXIS provides a related configuration descriptor for access control for web services, and provides a simple handler for access control (About Handler's Details "J2EE Web Service Development Series: Use Handler Enhance the function of web services "). By default, you only need to add a user in the configuration descriptor, and then automatically allow the role allowed in the WEB Server deployment descriptor.

First add a user in the AXIS's profile users.lst (in the web-inflicity), such as "Axisuser Pass", indicating that the user name is Axisuser, the password is Pass. Then add the case's Web service to add the deployment code shown in the routine 7 in Server-Config.WSDD.

Routines 7 Re-deploy PersonalTaxService

TYPE = "java: org.apache.axis.handlers.simpleauthenticationHandler" />

In this deployment descriptor, specifying the PersonalTAXService2 service can only be accessed by Axisuser. To make access control, you must also add SimpleAuthenticationHandler to the requesting handler chain.

You only need to modify the service endpoint URL of AuthClient code and access the user name, password, you can test the new web service, as shown in routine 8.

Routine 8 HandlerauthClient

Public Class HandlerauthClient

{

. . .

String endpointURL = "http: // localhost: 8080 / axis / services / personaltaxservice2? WSDL";

. . .

Call.getMessageContext (). SetUserName ("AxiSuser"); // Axis username.

Call.getMessageContext (). setpassword ("pass"); // password

. . .

Execute HandlerauthClient, you can access Web services smoothly; if you modify your username or password, you can't access it, this shows that Axis's Handler has effectively controlled access to Web services.

Accessing to control Axis using a Servlet filter (Filter) is in nature is run in a servlet mode, all we can deploy a servlet filter on a web application, and this filter is used to achieve access control.

The filter in the web application intercepts the request from the client, and then performs a series of processing, and finally sends the request to the target servlet. The working principle of the filter is shown below.

Figure 1 Filter working principle

The filter can be said to be the first way to enter the web server, which can determine whether the request continues forward, and can process the information in the request. If the filter is used to access the web service, it can determine whether the target service can be called successfully based on the client information.

The filter to be developed will be filtered according to the client IP address. If the client's IP address is in the limits, the target's web service cannot be accessed. The filter part of the filter is as follows.

Routine 9 limits access to Web services with filters

Package com.hellking.study.webservice;

Import javax.servlet.filterchain;

. . .

Public Class WebserveSfilter Implements Filter

{

// No IP address accessed

Static firm string [] DeniedIPList = new string [] {

"123.201",

"192.168", "25.46",

"124.0.0.1"

}

Public Boolean Isipdenided (String ipaddr)

{

...

}

// Method for filtering processing

Public Void Dofilter (Final ServletRequest Req, FiLterchain Chain) throws oews oews oews oews oews oews

{

HTTPSERVLETREQUEST HREQ = (httpservletRequest) REQ;

HttpservletResponse HRES = (httpservletResponse) res;

// httpsession session = hreq.getations ();

String clientip = Req.getRemoteAddr ();

System.out.println ("Start Filtering ...");

IF (iSIPDenied (Clientip))

{

// Verify is not successful, let the user log in.

Throw new servletexception ("No Performance Access this Web Service!");

}

Else

{

// Verify success, continue to process

Chain.dofilter (REQ, RES);

}

}

...

}

The WebServicesFilter filter limits all clients specified in DeniedIPLIST. After writing the filter, you need to specify this filter in the deployment descriptor of the web application and map the filter to the target URL. Of course, you can also develop other filters for access control, such as the web service client login, save the login information in the HTTP session, read the client information in the HTTP session when the client accesses the resource, read the client information in the HTTP session to decide Whether the client has permission to access the target resource.

In addition to writing a servlet filter, it is also necessary to configure it in web.xml, and map the filter to the target URI to filter. The following is the deployment descriptor of the filter.

Routine 10 deployed filters

WebServicesfilter

com.hellking.study.Webservice.WebservicesFilter

WebServicesfilter

/ services / *

URL-Pattern specifies the range of filters to be filtered. "/ Services / *" means that the URL starting with "/ services" will be filtered all, which is the default URL of the AXISSERVLET. By the above configuration, as long as the client calls the AXIS Web service, it will be filtered by the WebserveSfilter filter. If the client IP address is in the DeniedIPLIST of the filter, then the target service cannot be accessed.

Transfer Protocol web services using SSL as a web service can also use SSL as a transport protocol. Although the JAX-RPC does not force whether the SSL protocol is used, the HTTPS protocol is used under Tomcat.

Related Knowledge: SSL consists of two commonly working protocols: SSL Record Protocol and SSL Handshake Protocol. The SSL Record Protocol is established on the reliable transport protocol (such as TCP), providing support for basic functions such as data package, compression, encryption, etc. for high-level protocols; SSL handshake protocols are established on the SSL record protocol for actual data transmission. Before starting, the communication between communication, negotiate encryption algorithm, exchange encryption key, etc. The SSL handshake protocol contains two phases, and the first stage is used to establish a private communication channel, and the second phase is used for customer authentication. The first stage is the initialization phase of communication. At this stage, first, SSL requires the server to present a certificate to the browser; then the SSL software in the browser issues a randomized transmission key generated, this key is verified by the verified public The key is encrypted, the randomized transmission key is core confidential, only the customer's browser and this company's web server knows this digital sequence. The second phase of the main task is to authenticate the customer, and the server has been authenticated. Server direction client issues an authentication request message. After the customer receives the server's authentication request message, the customer issues its own certificate and listens to the authentication results of the other party. When the server receives the customer's certificate, return the authentication success message to the customer, otherwise returns an error message. Here, the handshake agreement ends.

To use the SSL protocol, the server has at least one private key and a certificate for verifying the identity. Private key is used in a key exchange algorithm that the certificate will be sent to the client to inform the server. If the SSL server wants to verify the client's identity, the client must have its own key library (including private key and certificate). The concept of trust library is introduced in JSSE, which is used to save the certificate. The client or server verifies the identity of the other party through a trust library.

Before using SSL, you must ensure that the system has JSSE installed. The JDK1.4 version is default and JSSE installed. If not installed, copy the downloaded JAR file to the% java_home / jre / lib / ext directory. In this way, the JSSE's operating environment is installed.

Below we use the JDK self-contained tool to create a key library and trust library.

1) Create a client's key library by using a command.

Keytool -Genkey -Alaias Hellking -keystore Server.Keystore -Keyalg RSA

Enter keystore password: Changeit

What is your name and last name?

[Unknown]: Hellking-Server

What is your organizational unit name?

[Unknown]: Huayuan

What is your organization name?

[Unknown]: Huayuan

What is your city or region name?

[Unknown]: beijing

What is your state or provincial name?

[Unknown]: beijing

What is the two-letter country code in this unit?

[Unknown]: CN

Cn = chen ya qiang, ou = huayuan, o = Huayuan, L = beijing, ST = beijing, c = CN correct?

[No]: Y

Enter master password

(If you pass the keystore password, press Enter):

After the above command is executed, a key library named Server.KeyStore will be obtained. 2) Generate the client's trust library. First output the RSA certificate:

KeyTool -Export -File Test_axis.cer -storepass changeit -keystore server.keystore

Then enter the RSA certificate into a new trust library file. This trust library is used by the client and is used to verify the identity of the server.

KeyTool-Import -File Test_axis.cer -storepass changeit -keystore client.truststore -Alias ​​ServerKey -noprompt

3) Create a client key library. Repeat step 1. Create a client's key library. You can also use the following command:

Keytool -Genkey-DName "CN = Hellking-Client, Ou = Tsinghua, O = TsingHUA, L = beijing, s = beijing, c = cn"

-storepass changeit -keystore client.keystore -keyalg rsa -keypass changeit

4) Generate the trust library of the server side.

Keytool -Export -File Test_axis.cer -storepass changeit -keystore client.keystore

KeyTool-Import -File Test_axis.cer -storepass changeit -keystore server.truststore -Alaias ClientKey -NoPrompt

The key library and trust library have been generated, and we copy the server-side key library (Server.trustStore) to Tomcat's directory.

The following needs to change the Tomcat configuration file (server.xml), add a deployment descriptor:

Routines 11 Configure the SSL protocol for Tomcat.

Maxthreads = "150" MINSPARETHREADS = "25" maxsparethreads = "75"

Enablelookups = "false" disableuploadtimeout = "true"

Acceptcount = "100" debug = "0" scheme = "https" secure = "true"

ClientAuth = "true" keystorefile = "k: /jakarta-tomcat-5.0.16/server.keystore" KeyStorePass = "changeit"

TrustStorefile = "k: /jakarta-tomcat-5.0.16/server.truststore" TrustStorePass = "Changeit"

SSLPROTOCOL = "TLS" />

ClientAuth parameters Develop whether the server is to verify the client certificate, if you specify true, then the client must support the server-side trusted certificate to respond to the client; if specified as false, the server does not need to verify the client's certificate.

Here, we deploy the PersonalTaxService once, add the following deployment code in Server-Config.WSDD.

Finally, we need to modify the client call, such as routine 12.

Routine 12 SSL client call

Package com.hellking.study.webservice;

.

Public Class SslauthClient

{

Static Final Double Salary = 5000;

Public static void main (string [] args)

{

Try {

// The server's URL, pay attention to the use of the SSL protocol, the prefix is ​​HTTPS.

String endpointurl = "https: // localhost: 8443 / axis / services / personaltaxservice3? WSDL";

.

// Due to the use of the certificate digital certificate, the username and password verification are not used.

//call.getMessageContext().setusername ("hellking ") ;..

//Call.getMessageContext().SetPassword ");

.

Double Ret = (Double) Call.invoke (New Object [] {new double (salary)});

System.out.println ("Use the SSL protocol to use the transfer protocol of the web service!");

System.out.println ("has been called successfully. Please refer to the output of the server!");

System.out.println ("Enter the wage" Salary ", pay personal income tax:" RET);

} catch (exception e) {

E.PrintStackTrace ();

}

}

}

Finally, use the command to perform the client program:

SET AXIS_LIB = K: /JAKARTA-TOMCAT-5.0.16/webapps/AXis/web-inf/lib

Set classpath =.;% Classpath%;% axis_lib% / wsdl4j.jar.jar;% AXIS_LIB% / AXIS.jar;% AXIS_LIB% / jaxrpc.jar;% AXIS_LIB%

/saaj.jar;%Axis_lib%/Commons-Discovery.jar;%AXIS_LIB% / Commons-logging.jar

Java -djavax.net.ssl.keystore = client.keystore /

-Djavax.net.ssl.keystorepassword = changeit /

-Djavax.net.ssl.truststore = Client.TrustStore /

com.hellking.study.Webservice.sslauthClient

Parameter Interpretation: Specify the client key library through -djavax.net.ssl.keystore, -djavax.net.ssl.trustStore to specify the client letter library. The final output is as follows:

Use the SSL protocol as a transfer protocol for web services!

Has been successfully called. See the output of the server!

Enter the salary of 5,000.0 yuan, you should pay personal income tax: 445.0

Summary, the next step Using the basic authentication method in the web application model to configure the security access of the web service and use the AXIS's Handler, Servlet filter for access control, they are some lightweight control web service security solutions, because It is spread unpryptable information on the network. After using SSL as the transfer protocol, the information is encrypted on the network, but the resource consumption is much consuming, and the client requirements are strict (must support SSL), and the convenience of Web service access is not met. The next part will introduce how to implement WS-Security in the AXIS development tool in an environment with high security requirements.

Download sample code here.

Reference

VeriSign Trust Services Integration Kit Configure Tomcat 4 Use SSL to Develop Web Services with JAX-RPC: Servlet As Web Services Endpoint Web Service Security Topic Apache Axis User's Guides: http: //ws.apache.org/axis/ JAX-RPC API SSL3. 0 Specifications Keytool- Key and Certificate Management Tool The Tomcat 5 Servlet / JSP Container SSL Configuration How-to J2EE Web Services Development Series: Use Handler to enhance web services

转载请注明原文地址:https://www.9cbs.com/read-83010.html

New Post(0)