Restricting access to Web services with filters __web

Source: Internet
Author: User
Tags wsdl
Using Axis's handler for access control

Axis provides the associated configuration descriptor for access control for Web services and provides a simple handler of access control (see the Handler Web Services Development Series six: Using handler to enhance the functionality of Web services). By default, you simply add users to the configuration descriptor and then automatically allow roles in the deployment descriptor of the Web server.

First, add a user, such as "Axisuser Pass", to the axis's profile users.lst (located in the Web-inf directory), which means that the user name is Axisuser, and the password is. Then redeploy the case Web service and add the deployment code shown in routine 7 in SERVER-CONFIG.WSDD.


Routine 7 Redeployment Personaltaxservice

<service name= "PersonalTaxService2" provider= "Java:rpc" >
<parameter name= "Allowedmethods" value= "*"/>
<parameter name= "ClassName" value= "Com.hellking.study.webservice.PersonalTaxService"/>
<parameter name= "Allowedroles" value= "Axisuser"/>
<requestFlow>
Type= "Java:org.apache.axis.handlers.SimpleAuthenticationHandler"/>
</requestFlow>
</service>



In this deployment descriptor, the specified PersonalTaxService2 service can only be accessed by Axisuser, and in order for access control to take effect, Simpleauthenticationhandler must also be added to the request handler chain.

You can test the new Web service by simply modifying the service endpoint URL and access username and password of the Authclient code, as shown in routine 8.


Routine 8 handlerauthclient

public class Handlerauthclient
{
。。。
String Endpointurl = "http://localhost:8080/axis/services/PersonalTaxService2?wsdl";
。。。
Call.getmessagecontext (). Setusername ("Axisuser"), user name in//axis.
Call.getmessagecontext (). SetPassword ("Pass");//password
。。。



Perform handlerauthclient, access to Web services smoothly, and if you modify a username or password, you cannot access it, indicating that Axis's handler has effective control over access to the Web service.

Access control using the servlet filter (filter) the Web server at axis is essentially a servlet operation, and all of us can deploy a servlet filter on a Web application that achieves the effect of access control.

The filters in the Web application intercept requests that come in from the client, then perform a series of processing, and finally send the request to the target servlet. The filter works as shown in the following illustration.


Fig. 1 Working principle of filter


A filter can be said to be the first pass into a Web server, it can determine whether the request continues forwarding forward, but also can handle the information in the request. If the filter is used to access control of a Web service, it can determine whether the target's service can be successfully invoked based on client information.

The filter to be developed will be filtered according to the client IP address, and if the client's IP address is restricted, the target Web service cannot be accessed. The filter section code is as follows.


Routine 9 restricting access to Web services with filters

Package com.hellking.study.webservice;

Import Javax.servlet.FilterChain;
。。。
public class Webservicesfilter implements Filter
{
IP address with no access
Static final string[] Deniediplist=new string[]{
"123.201",
"192.168",
"25.46",
"124.0.0.1"
};
public boolean isipdenied (String ipaddr)
{
...
}

Method of filtration Treatment
public void Dofilter (final servletrequest req,final servletresponse res,filterchain chain)
Throws Ioexception,servletexception
{
HttpServletRequest hreq = (httpservletrequest) req;
HttpServletResponse hres = (httpservletresponse) res;
HttpSession session = Hreq.getsession ();
String clientip=req.getremoteaddr ();
System.out.println ("Start filtering ...") ");
if (isipdenied (ClientIP))
{
Validation unsuccessful, let the user log in.
throw new Servletexception ("No access to this Web service." ");
}
Else
{
Validation successful, continue processing
Chain.dofilter (Req,res);

}

}
...
}



The Webservicesfilter filter restricts all clients specified in the deniediplist. After you have written the filter, you need to specify the use of this filter in the deployment descriptor for the Web application and map the filter to the destination URL. Of course, you can also develop other filters for access control, such as when a Web service client logs on, stores the login information in an HTTP session, and when the client accesses a restricted resource, reads the client information in the HTTP session to determine whether the client has access to the target resource.

In addition to writing a servlet filter implementation class, you need to configure it in Web.xml and map the filter to the target URI to be filtered. The following is a deployment descriptor for the filter.


Routine 10 Department Filter

<filter>
<filter-name>WebServicesFilter</filter-name>
<filter-class>com.hellking.study.webservice.WebServicesFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>WebServicesFilter</filter-name>
<url-pattern>/services/*</url-pattern>
</filter-mapping>



Url-pattern specifies the scope of the filter to filter. "/services/*" means that URLs starting with "/services" will all be filtered, which is exactly the Axisservlet default URL. With the above configuration, as long as the client invokes the Axis Web service, it is filtered by the Webservicesfilter filter. If the client IP address is in the deniediplist of the filter, the target service cannot be accessed.



Using SSL as a transport protocol for Web services

Web services can also use SSL as a transport protocol. Although Jax-RPC does not enforce the use of the SSL protocol, the HTTPS protocol is used under Tomcat.

Related knowledge:

SSL consists of two protocols that work together: The SSL record Protocol (SSL capture Protocol) and the SSL Handshake Protocol (SSL handshake Protocol). The SSL recording protocol is based on a reliable transmission protocol (such as TCP), which provides the basic functions of data encapsulation, compression and encryption for the High-level Protocol. The SSL handshake protocol is based on the SSL recording Protocol, which is used to authenticate, negotiate and encrypt the encryption algorithm before the actual data transmission begins. Exchange encryption keys, and so on.

The SSL handshake protocol consists of two phases, the first phase is used to establish a private communication channel, and the second phase is used for customer authentication. The first stage is the initial phase of communication, in which SSL requires the server to present a certificate to the browser, and then the SSL software in the browser sends the server a randomly generated transmission key, which is encrypted by the authenticated public key, and the randomly generated transmission key is the core secret, Only the client's browser and this company's Web server know this number sequence. The second phase of the main task is to authenticate the customer, at this time the server has been certified. The server sends the authentication request message to the customer. When the client receives the authentication request message from the server, it issues its own certificate and listens for the authentication result of the other side loopback. And when the server receives the customer's certificate, the customer Loopback authentication Success message, otherwise return error message. So far, the handshake agreement is all over.

To use the SSL protocol, the server has at least one private key and one certificate for authentication. The private key is used in the key exchange algorithm, and the certificate is sent to the client to notify the server side of the identity. If the SSL server verifies the identity of the client, the client must also have its own keystore (including private keys and certificates). The concept of the Trust Library (Truststore) is introduced in Jsse, which is the database used to hold certificates. The client or server verifies the identity of the other through the Trust library.

Before using SSL, you must ensure that Jsse is installed on the system. The JDK1.4 version defaults and installs the Jsse. 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 JDK's own tools to create keystore and trust libraries.

1 Create a server-side keystore by using a command.


Keytool-genkey-alias Hellking-keystore Server.keystore-keyalg RSA
Enter KeyStore Password: Changeit
What is your first and last name?
[Unknown]: Hellking-server
What is the name of your organizational unit?
[Unknown]: Huayuan
What is the name of your organization.
[Unknown]: Huayuan
What is the name of your city or region.
[Unknown]: Beijing
What is the name of your state or province.
[Unknown]: Beijing
What is the two-letter country code for that unit?
[Unknown]: CN
Cn=chen ya Qiang, Ou=huayuan, O=huayuan, l=beijing, st=beijing, C=CN right.
[No]: Y

Enter (press ENTER if same as KeyStore password):



When the above command is completed, a keystore named Server.keystore is obtained.

2 Generate a trust library for the client. First output RSA Certificate:


Keytool-export-file Test_axis.cer-storepass Changeit-keystore Server.keystore



The RSA certificate is then entered into a new trust library file. This trust library is used by the client to authenticate the server side.


Keytool-import-file test_axis.cer-storepass Changeit-keystore Client.truststore-alias serverkey-noprompt



3 Create the Client key library. Repeat step 1 to create the client's key library. You can also do this by using 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 a server-side trust library.


Keytool-export-file Test_axis.cer-storepass Changeit-keystore Client.keystore
Keytool-import-file test_axis.cer-storepass Changeit-keystore Server.truststore-alias clientkey-noprompt



Creating a KeyStore and trust library, we copy the server-side KeyStore (Server.keystore) and trust Library (Server.truststore) to a directory of Tomcat.

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


Routine 11 configures the SSL protocol for Tomcat.

<connector port= "8443"
maxthreads= "minsparethreads=" maxsparethreads= "75"
Enablelookups= "false" disableuploadtimeout= "true"
Acceptcount= "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"/>



The ClientAuth parameter specifies whether the server will authenticate the client certificate and, if true, the client must support the server-side trustworthy certificate before the server can respond to the client, and if False, the server does not need to authenticate the client's certificate.

Here, we deploy personaltaxservice again, adding the following deployment code to SERVER-CONFIG.WSDD.


<service name= "PersonalTaxService3" provider= "Java:rpc" >
<parameter name= "Allowedmethods" value= "*"/>
<parameter name= "ClassName" value= "Com.hellking.study.webservice.PersonalTaxService"/>
</service>



Finally we need to modify the client Invoker, as shown in routine 12.


Routine SSL client caller

Package com.hellking.study.webservice;
....
public class Sslauthclient
{
static final double salary=5000;
public static void Main (String [] args)
{
try {
Server-side URL, note that after using the SSL protocol, the prefix is HTTPS.
String Endpointurl = "https://localhost:8443/axis/services/PersonalTaxService3?wsdl";
....
User name and password authentication are not used because certificate digital certificates are used.
Call.getmessagecontext (). Setusername ("hellking");.
Call.getmessagecontext (). SetPassword ("simplewebservices");
....
DOUBLE ret = (double) call.invoke (new Object [] {new Double (Salary)});
System.out.println ("uses the SSL protocol as a transport protocol for Web services.) ");
System.out.println ("has been successfully invoked.) Please refer to the output of the service side! ");
SYSTEM.OUT.PRINTLN ("input wage" +salary+ "yuan, should pay personal income tax:" +ret);
catch (Exception e) {
E.printstacktrace ();
}
}
}



Finally, use the command to execute 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 explanation: Specifies the client keystore by-djavax.net.ssl.keystore,-djavax.net.ssl.truststore to specify the client trust library.

The final output results are as follows:


Use the SSL protocol as a transport protocol for Web services.
has been successfully invoked. Please refer to the output of the service side!
Enter salary 5000.0 Yuan, should pay personal income tax: 445.0

trackback:http://tb.blog.csdn.net/trackback.aspx?postid=667484

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.