Apache CXF: JAX-RS Restful web service + Integrating with Spring Security

In this article, we will integrate Spring Security features to protect the access to the exposed web services. And only authorized users can access this protected services

Refer <Spring-Security-Database> and <ApacheCXF-XML-JSON-IO> articles to understand this article

Annotation Used

  • @Path (javax.ws.rs.Path)
  • @GET (javax.ws.rs.GET)
  • @POST (javax.ws.rs.POST)
  • @PUT (javax.ws.rs.PUT)
  • @DELETE (javax.ws.rs.DELETE)
  • @PathParam (javax.ws.rs.PathParam)
  • @Consumes (javax.ws.rs.Consumes)
  • @Produces (javax.ws.rs.Produces)
  • @Service (org.springframework.stereotype.Service)
  • MediaType (javax.ws.rs.core.MediaType)

Technology Used

  • Java 1.7
  • Eclipse Luna IDE
  • Spring-4.0.0-RELEASE
  • Apache-CXF-3.0.0
  • Apache Maven 3.2.1
  • Apache Tomcat 7.0.54
  • MySql-Connector-Java-5.1.31

Mavenize or download required jars

Add Apache-CXF-3.0.0, Spring-4.0.0-RELEASE & MySql-Connector-Jav-5.1.31 dependencies to pom.xml

	<dependencies>
			<!-- jstl for jsp page -->
			<dependency>
				<groupId>jstl</groupId>
				<artifactId>jstl</artifactId>
				<version>${jstl.version}</version>
			</dependency>

			<!-- Apache CXF -->
			<dependency>
				<groupId>org.apache.cxf</groupId>
				<artifactId>cxf-rt-frontend-jaxrs</artifactId>
				<version>${cxf.version}</version>
			</dependency>
			<dependency>
				<groupId>org.apache.cxf</groupId>
				<artifactId>cxf-rt-transports-http</artifactId>
				<version>${cxf.version}</version>
			</dependency>
			<dependency>
				<groupId>org.apache.cxf</groupId>
				<artifactId>cxf-rt-transports-http-jetty</artifactId>
				<version>${cxf.version}</version>
			</dependency>

			<!-- for JSON support in Apache-CXF Restful web service -->
			<dependency>
				<groupId>org.codehaus.jackson</groupId>
				<artifactId>jackson-jaxrs</artifactId>
				<version>${jackson.version}</version>
			</dependency>

			<!-- MySql-Connector -->
			<dependency>
				<groupId>mysql</groupId>
				<artifactId>mysql-connector-java</artifactId>
				<version>5.1.31</version>
			</dependency>

			<!-- Spring framework -->
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-core</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-context</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-jdbc</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-web</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-webmvc</artifactId>
				<version>${spring.version}</version>
			</dependency>

			<!-- Spring Security 3.2.0.RELEASE Framework -->
			<dependency>
				<groupId>org.springframework.security</groupId>
				<artifactId>spring-security-core</artifactId>
				<version>${spring.security.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework.security</groupId>
				<artifactId>spring-security-web</artifactId>
				<version>${spring.security.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework.security</groupId>
				<artifactId>spring-security-config</artifactId>
				<version>${spring.security.version}</version>
			</dependency>

			<!-- Apache HTTP components for writing test client -->
			<dependency>
				<groupId>commons-httpclient</groupId>
				<artifactId>commons-httpclient</artifactId>
				<version>3.1</version>
				<scope>compile</scope>
			</dependency>
			<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpclient</artifactId>
				<version>${apache.httpcomponents.version}</version>
				<scope>compile</scope>
			</dependency>
			<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpcore</artifactId>
				<version>${apache.httpcomponents.version}</version>
				<scope>compile</scope>
			</dependency>
			<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpmime</artifactId>
				<version>${apache.httpcomponents.version}</version>
				<scope>compile</scope>
			</dependency>
	</dependencies>

Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the spring site or maven repository and include them in the classpath

JAXB – Generating java source files from XSD

Steps to generate java-sources from XML Schema Definition (XSD)

  • configure JAXB Maven plugin in pom.xml
  • write well-defined XSD for your service
  • use maven command “mvn generate-sources” to generate java source files

Configure JAXB Maven plugin

<!-- JAXB plugin to generate-sources from XSD -->
<plugin>
	<groupId>org.codehaus.mojo</groupId>
	<artifactId>jaxb2-maven-plugin</artifactId>
	<version>1.5</version>
	<executions>
		<execution>
			<goals>
				<goal>xjc</goal><!-- xjc/generate -->
			</goals>
			<configuration>
				<outputDirectory>${basedir}/generated/java/source</outputDirectory>
				<schemaDirectory>${basedir}/src/main/resources/com/apache/cxf/spring/security/entities
				</schemaDirectory>
				<schemaFiles>*.xsd</schemaFiles>
				<schemaLanguage>XMLSCHEMA</schemaLanguage>
				<extension>true</extension>
				<args>
					<arg>-XtoString</arg>
				</args>
				<plugins>
					<plugin>
						<groupId>org.jvnet.jaxb2_commons</groupId>
						<artifactId>jaxb2-basics</artifactId>
						<version>0.6.4</version>
					</plugin>
				</plugins>
			</configuration>
		</execution>
	</executions>
</plugin>

Player.xsd

Below XSD contains two elements with name “PlayerType” and “PlayerListType”

  • PlayerType contains four attributes namely playerId, name, age and matches
  • PlayerListType which returns list of PlayerType
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	targetNamespace="http://benchresources.in/cdm/Player" xmlns:tns="http://benchresources.in/cdm/Player"
	elementFormDefault="qualified">

	<!-- player object with four attributes -->
	<xsd:element name="PlayerType">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element name="playerId" type="xsd:int" />
				<xsd:element name="name" type="xsd:string" />
				<xsd:element name="age" type="xsd:int" />
				<xsd:element name="matches" type="xsd:int" />
			</xsd:sequence>
		</xsd:complexType>
	</xsd:element>

	<!-- an object to contain lists of players referencing above player object -->
	<xsd:element name="PlayerListType">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element ref="tns:PlayerType" minOccurs="0"
					maxOccurs="unbounded" />
			</xsd:sequence>
		</xsd:complexType>
	</xsd:element>
</xsd:schema>

Run mvn generate-sources

Look at the generated java source files in the generated folder

PlayerType.java

package in.benchresources.cdm.player;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "playerId",
    "name",
    "age",
    "matches"
})
@XmlRootElement(name = "PlayerType")
public class PlayerType {

    protected int playerId;
    @XmlElement(required = true)
    protected String name;
    protected int age;
    protected int matches;

    public int getPlayerId() {
        return playerId;
    }
    public void setPlayerId(int value) {
        this.playerId = value;
    }
    public String getName() {
        return name;
    }
    public void setName(String value) {
        this.name = value;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int value) {
        this.age = value;
    }
    public int getMatches() {
        return matches;
    }
    public void setMatches(int value) {
        this.matches = value;
    }
}

PlayerListType.java

package in.benchresources.cdm.player;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "playerType"
})
@XmlRootElement(name = "PlayerListType")
public class PlayerListType {

    @XmlElement(name = "PlayerType")
    protected List<PlayerType> playerType;
    public List<PlayerType> getPlayerType() {
        if (playerType == null) {
            playerType = new ArrayList<PlayerType>();
        }
        return this.playerType;
    }
}

Directory Structure

Before moving on, let us understand the directory/package structure once you create project in Eclipse IDE
Maven has to follow certain directory structure

  • src/test/java –> test related files, mostly JUnit test cases
  • src/main/java –> create java source files under this folder
  • src/main/resources –> all configuration files placed here
  • generated/java/source –> generated java source files are placed here
  • Maven Dependencies or Referenced Libraries –> includes jars in the classpath
  • WEB-INF under webapp –> stores web.xml & other configuration files related to web application

Project Structure (Package Explorer view in Eclipse)

1_ApacheCXF-Spring-Security_Project_Structure_In_Eclipse

Jars Libraries Used in the Project (Maven Dependencies)

It is quite long, just shown starting 60% of jars

2_ApacheCXF-Spring-Security_Jars_In_Classpath

Web application

For any web application, entry point is web.xml which describes how the incoming http requests are served / processed. Further, it describes about the global-context and local-context param (i.e.; <context-param> & <init-param>) for loading files particular to project requirements & contains respective listener

With this introduction, we will understand how we configured web.xml for Apache CXF JAX-RS Restful web service + integrating Spring Security

web.xml (the entry point –> under WEB-INF)

This web.xml file describes,

  • Like any JEE web framework register org.apache.cxf.transport.servlet.CXFServlet with servlet container
  • All http requests with URL pattern “/services/*” will be sent to the registered servlet called “CXFServlet” (org.apache.cxf.transport.servlet.CXFServlet)
  • <context-param> with its attributes describes the location of the “apache-cxf-service.xml”“ApplicationContext.xml”  and “Spring-Security.xml” files from where it has to be loaded. We will discuss briefly about these files
  • <welcome-file-list> files under this tag is the start-up page
  • Servlet filter called “DelegatingFilterProxy” with url-pattern /* intercepts incoming http requests and enter Spring Security framework for security checks to authenticate users
  • “spring-security.xml” describes which URL needs to be intercepted along with their roles/credentials
  • NOTE: don’t change this name “springSecurityFilterChain”

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

	<display-name>ApacheCXF-Spring-Security</display-name>

	<!-- Spring Security -->
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
		<dispatcher>REQUEST</dispatcher>
		<dispatcher>FORWARD</dispatcher>
		<dispatcher>INCLUDE</dispatcher>
		<dispatcher>ERROR</dispatcher>
	</filter-mapping>

	<!-- Apache CXF -->
	<servlet>
		<servlet-name>CXFServlet</servlet-name>
		<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>CXFServlet</servlet-name>
		<url-pattern>/services/*</url-pattern>
	</servlet-mapping>

	<!-- web context param -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			WEB-INF/apache-cxf-services.xml,
			WEB-INF/ApplicationContext.xml,
			WEB-INF/spring-security.xml
		</param-value>
	</context-param>

	<!-- listener -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- welcome file list -->
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Apache CXF services

Apache CXF comes with spring based configuration, so it is easy to register beans in the spring container much like we do any bean in spring application. CXFServlet receives the incoming http requests and invokes corresponding registered beans in according to http url path

NOTE: For this Restful JAX-RS application, we are using Spring annotations to define/register beans in the spring container thereby avoiding lot of boilerplate code to write

This apache-cxf-services.xml describes,

  • <jaxrs:server /> defines which service bean to be invoked for the incoming http requests. In this case, any wild card pattern “/” will invoke “playerService” which is registered as service bean using @Service(“playerService”) annotation (on top of the PlayerServiceImpl java class)
  • bean with id=”jsonProvider” defined to support JSON format
  • bean with id=”jaxbXmlProvider” defined to support XML format
  • <jaxrs:extensionMappings> with this element you can use dot notation to get result in the required format, instead of supplying the accept header parameter
  • NOTE: For two different beans we can have two different url-pattern(address) like
		<jaxrs:server id="restContainer" address="/">
			<jaxrs:serviceBeans>
				<ref bean="playerService" />
			</jaxrs:serviceBeans>
		</jaxrs:server>
		
		<jaxrs:server id="twotest" address="/two">
			<jaxrs:serviceBeans>
				<ref bean="testService" />
			</jaxrs:serviceBeans>
		</jaxrs:server>

apache-cxf-services.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
	xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">

	<!-- to support Java-to-JSON and vice-versa conversion -->
	<bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />

	<!-- to support Java-to-XML and vice-versa conversion -->
	<bean id="jaxbXmlProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider" />

	<!-- CXFServlet configured in web.xml sends requests here -->
	<jaxrs:server id="restContainer" address="/">
		<jaxrs:serviceBeans>
			<ref bean="playerService" />
		</jaxrs:serviceBeans>

		<jaxrs:extensionMappings>
			<entry key="json" value="application/json" /> <!-- use .json to get data in JSON format -->
			<entry key="xml" value="application/xml" />   <!-- use .xml to get data in XML format -->
		</jaxrs:extensionMappings>

		<jaxrs:providers>
			<ref bean="jsonProvider" />
			<ref bean="jaxbXmlProvider" />
		</jaxrs:providers>
	</jaxrs:server>
</beans>

Spring Application Context

Segregated XML configuration for Apache CXF JAX-RS service and Spring context for modular approach. All spring related configuration are placed inside this context file

This ApplicationContext.xml describes,

  • <context:annotation-config /> to activate annotation on the registered beans with application context
  • <context:component-scan base-package=”” /> tag scans all classes & sub-classes under the value of base-package attribute and register them with the Spring container
  • bean with id=”dataSource” defines values for driverClassName, url, username and password for MySql database

ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<!-- to activate annotations in beans already registered in the application
		context -->
	<context:annotation-config />

	<!-- scans packages to find and register beans within the application context -->
	<!-- register beans for handling incoming HTTP requests -->
	<context:component-scan base-package="com.apache.cxf.spring.security.service" />

	<!-- MySql dataSource configuration -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/benchresources" />
		<property name="username" value="root" />
		<property name="password" value="" />
	</bean>
</beans>

MySql Database

To move user credentials and their ROLES, you have to create tables and insert records. Let’s do it

Create USERS table
# USERS

create table users (
    username varchar(50) not null primary key,
    password varchar(60) not null,
    enabled boolean not null
) engine = InnoDb;

Create AUTHORITIES table
# AUTHORITIES

create table authorities (
    username varchar(50) not null,
    authority varchar(50) not null,
    foreign key (username) references users (username),
    unique index authorities_idx_1 (username, authority)
) engine = InnoDb;

Let’s insert records in both tables

# INSERT records into USERS table

INSERT INTO `users`(`username`, `password`, `enabled`) VALUES ('Arun', 
'$2a$10$BwyjwGRWc4gMk2Y1e2jzie.FVYrfgxV0.aHgdU1VM6E.Rf0ZYoaWa, 1);
INSERT INTO `users`(`username`, `password`, `enabled`) VALUES ('Jeremy', 
'$2a$10$EHmzwTcEFS1IUZ.hhsMw.uZvG2uwH7fOS1nh/fcIiAvmXg3LwdVP.', 1);
INSERT INTO `users`(`username`, `password`, `enabled`) VALUES ('Jing', 
'$2a$10$twiIh66bjFBWBYZPWOrc1uS/KRCdT61Z5wFdpJGdeHwY2HeCZ.J.a, 1);

# INSERT records into AUTHORITIES table

INSERT INTO authorities (username, authority) VALUES ('Arun', 'ROLE_ADMIN');
INSERT INTO authorities (username, authority) VALUES ('Jeremy', 'ROLE_USER');
INSERT INTO authorities (username, authority) VALUES ('Jing', 'ROLE_USER');

How to get hashed or encoded password using BCryptPasswordEncoder

PasswordHashing.java

package test.spring.series.security;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

public class PasswordHashing {

	// http://docs.spring.io/spring-security/site/docs/3.2.4.RELEASE/reference/htmlsingle/#ns-getting-started
	public static void main(String[] args) {

		String[] originalPassword = {"arun123", "jeremy123", "jing123"};
		PasswordEncoder encoder = new BCryptPasswordEncoder();
		String hashedPassword = "";

		System.out.println("ORIGINAL \t HASHED");
		System.out.println("=========\t=======");
		for(String password : originalPassword){
			hashedPassword = encoder.encode(password);
			System.out.println(password + "\t\t" + hashedPassword);
		}
	}
}

Result in console

ORIGINAL 	 HASHED
=========	=======
arun123	        $2a$10$BwyjwGRWc4gMk2Y1e2jzie.FVYrfgxV0.aHgdU1VM6E.Rf0ZYoaWa
jeremy123	$2a$10$EHmzwTcEFS1IUZ.hhsMw.uZvG2uwH7fOS1nh/fcIiAvmXg3LwdVP.
jing123	        $2a$10$twiIh66bjFBWBYZPWOrc1uS/KRCdT61Z5wFdpJGdeHwY2HeCZ.J.a

Spring Security Configuration

This Spring Security configuration file describes the security URL to be intercepted and login details for that particular role

  • First element <security:http /> with pattern describes which are all incoming http requests needs to be intercepted
  • Second element with <security:authentication-manager /> defines the credentials (username/password) for every role. For example, ROLE_ADMIN, ROLE_USER, etc
  • <security:password-encoder ref=“bcryptPasswordEncoder” /> refers hashing algorithm used for this application, which is BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)
  • bcryptPasswordEncoder bean defines encoding algorithm with two constructor-arg viz. name & strength. Default strength value is 10
  • <security:jdbc-user-service /> defines two queries to authenticate users credentials along with their ROLES, interacting dataSource configured in the ApplicationContext.xml which is MySql database in our example

spring-security.xml

<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<security:http auto-config="true">
		<security:intercept-url pattern="/services/**"
			access="ROLE_USER" />
	</security:http>

	<security:authentication-manager>
		<security:authentication-provider>
			<security:password-encoder ref="bcryptPasswordEncoder" />
			<security:jdbc-user-service
				data-source-ref="dataSource"
				users-by-username-query="select username, password, enabled from users where username=?"
				authorities-by-username-query="select username, authority from authorities where username =?  " />
		</security:authentication-provider>
	</security:authentication-manager>

	<beans:bean id="bcryptPasswordEncoder"
		class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
		<beans:constructor-arg name="strength" value="10" />
	</beans:bean>
</beans:beans>

Let’s see coding in action

 

URL Pattern

Http URL for any common web application is http://<server>:<port>/<context-root>/<from_here_application_specific_path>

In our example, we are going to deploy war into Tomcat 7.0 server so our server & port are localhost and 8080 respectively. Context root is the project name i.e.; ApacheCXF-Spring-Security. Initial path for this application is http://localhost:8080/ApacheCXF-Spring-Security

We have configured “/services/*” as url-pattern for the CXFServlet in web.xml and at interface-level (or say class-level) path configured is “/player” using @Path annotation. Next, respective path for each method annotated with @Path (method-level)

Player Service interface

Defines simple CURD operations

  • @POST          – create/inserts a new resource (new player)
  • @GET           – read/selects internal resource representation based on the playerId
  • @PUT            – update/modifies an internal resource representation (modify player)
  • @DELETE       – delete/removes a resource (delete player)
  • @GET           – retrieves all players (get all players)

Let’s discuss @Produces, @Consumes and MediaType

@Consumes

Define which MIME type is consumed by this method. For this example, exposed methods supports both XML & JSON formats i.e.; methods are annotated with @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})

Note: When Content-Type is not specified in the header, then by default it expects request body in “application/x-www-form-urlencoded”. So, Content-Type needs to be set/sent in the header

@Produces

Define which MIME type it will produce. For this example, exposed methods produce response in both XML & JSON formats i.e.; methods are annotated with @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})

Note: By default, when invoked it returns the response in XML as it is the first string in the array. So, to get the response in the JSON format then set accept=”application/json” in the header

Most widely used Media Types are

  • MediaType.APPLICATION_XML,
  • MediaType.APPLICATION_JSON,
  • MediaType.TEXT_PLAIN,
  • MediaType.TEXT_XML,
  • MediaType.APPLICATION_FORM_URLENCODED,
  • etc

NOTE: It’s always a good programming practice to do code-to-interface and have its implementation separately

IPlayerService.java

package com.apache.cxf.spring.security.service;

import in.benchresources.cdm.player.PlayerListType;
import in.benchresources.cdm.player.PlayerType;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/playerservice")
public interface IPlayerService {

	// Basic CRUD operations for Player Service

	// http://localhost:8080/ApacheCXF-Spring-Security/services/playerservice/addplayer
	@POST
	@Path("addplayer")
	@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	@Produces({MediaType.APPLICATION_FORM_URLENCODED})
	public String createOrSaveNewPLayerInfo(PlayerType playerType);

	// http://localhost:8080/ApacheCXF-Spring-Security/services/playerservice/getplayer/188
	@GET
	@Path("getplayer/{id}")
	@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public PlayerType getPlayerInfo(@PathParam("id") int playerId);

	// http://localhost:8080/ApacheCXF-Spring-Security/services/playerservice/updateplayer
	@PUT
	@Path("updateplayer")
	@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	@Produces({MediaType.APPLICATION_FORM_URLENCODED})
	public String updatePlayerInfo(PlayerType playerType);

	// http://localhost:8080/ApacheCXF-Spring-Security/services/playerservice/deleteplayer
	@DELETE
	@Path("deleteplayer")
	@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON,})
	@Produces({MediaType.APPLICATION_FORM_URLENCODED})
	public String deletePlayerInfo(PlayerType playerType);

	// http://localhost:8080/ApacheCXF-Spring-Security/services/playerservice/getallplayer
	@GET
	@Path("getallplayer")
	@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public PlayerListType getAllPlayerInfo();
}

Player Service implementation

Implements above interface. Self explanatory !!

PlayerServiceImpl.java

package com.apache.cxf.spring.security.service;

import in.benchresources.cdm.player.PlayerListType;
import in.benchresources.cdm.player.PlayerType;

import org.springframework.stereotype.Service;

@Service("playerService")
public class PlayerServiceImpl implements IPlayerService {

	/**
	 * returns a String value with SUCCESS message after adding a player
	 */
	@Override
	public String createOrSaveNewPLayerInfo(PlayerType playerType) {

		// get the player information from formal arguments and inserts into database & return playerId (primary_key)
		return "Player information saved successfully with PLAYER_ID " + 188;
	}

	/**
	 * retrieves a player object based on the playerId supplied in the formal argument using @PathParam
	 */
	@Override
	public PlayerType getPlayerInfo(int playerId) {

		// retrieve player based on the id supplied in the formal argument
		PlayerType getplayer = new PlayerType();
		getplayer.setPlayerId(playerId);
		getplayer.setName("Stephen Fleming");
		getplayer.setAge(41);
		getplayer.setMatches(111);
		return getplayer;
	}

	/**
	 * returns a String value with SUCCESS message after updating a player
	 */
	@Override
	public String updatePlayerInfo(PlayerType playerType) {

		// update player info & return SUCCESS message
		return "Player information updated successfully";
	}

	/**
	 * returns a String value with SUCCESS message after deleting a player
	 */
	@Override
	public String deletePlayerInfo(PlayerType playerType) {

		// delete player info & return SUCCESS message
		return "Player information deleted successfully";
	}

	/**
	 * retrieves all players stored
	 */
	@Override
	public PlayerListType getAllPlayerInfo() {

		// create a object of type PlayerType which takes player objects in its list
		PlayerListType playerListType = new PlayerListType();

		// player 1 info
		PlayerType playerOne = new PlayerType();
		playerOne.setPlayerId(197);
		playerOne.setName("Nathan Astle");
		playerOne.setAge(43);
		playerOne.setMatches(83);
		playerListType.getPlayerType().add(playerOne); // add to playerListType

		// player 2 info
		PlayerType playerTwo = new PlayerType();
		playerTwo.setPlayerId(180);
		playerTwo.setName("Dion Nash");
		playerTwo.setAge(43);
		playerTwo.setMatches(32);
		playerListType.getPlayerType().add(playerTwo); // add to playerListType

		return playerListType;
	}
}

 

Deployment

  • Run maven command to build the war : mvn clean install (use command prompt or integrated maven in eclipse IDE)
  • Copy the war file from the target folder
  • Paste it into apache tomcat (webapps folder)
  • Start the tomcat server

Test the service !!

 

Testing

There are many ways to do testing

  • Copy URL of GET service into web browser
  • Advanced REST client from Google Chrome
  • Rest client from Mozilla Firefox Add On
  • Write your own client for example, Java client using httpcomponents from Apache
  • JDK’s in-built classes like HttpURLConnection (Java client)

 

1. Using RestClient from Mozilla Firefox Add-On

Every service tested setting up header parameters “accept” & “Content-Type” in the request

Before proceeding with testing of every service, you must provide correct credentials as spring-security will intercept request http url with pattern “/services/**”. See spring-security.xml file for details

3_ApacheCXF-Spring-Security_Basic_Authentication_user_password

1.1

First service: @POST (createOrSaveNewPLayerInfo())
URL: http://localhost:8080/ApacheCXF-Spring-Security/services/playerservice/addplayer
Request:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerType xmlns="http://benchresources.in/cdm/Player">
	<playerId>188</playerId>
	<name>Stephen Fleming</name>
	<age>41</age>
	<matches>111</matches>
</PlayerType>

Content-Type: application/xml
accept: application/x-www-form-urlencoded
Response: Player information saved successfully with PLAYER_ID 188
4_ApacheCXF-Spring-Security_playerservice_addplayer_xml

1.2

Second service: @GET (getPlayerInfo())
URL:http://localhost:8080/ApacheCXF-Spring-Security/services/playerservice/getplayer/188
Request: None
Content-Type: application/x-www-form-urlencoded
accept: application/json
Response:

{
  "playerId": 188,
  "name": "Stephen Fleming",
  "age": 41,
  "matches": 111
}

5_ApacheCXF-Spring-Security_playerservice_getplayer_json

1.3

Third service: @PUT (updatePlayerInfo())
URL:http://localhost:8080/ApacheCXF-Spring-Security/services/playerservice/updateplayer
Request:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerType xmlns="http://benchresources.in/cdm/Player">
	<playerId>188</playerId>
	<name>Stephen Fleming</name>
	<age>41</age>
	<matches>111</matches>
</PlayerType>

Content-Type: application/xml
accept: application/x-www-form-urlencoded
Response: Player information updated successfully
6_ApacheCXF-Spring-Security_playerservice_updateplayer_xml

1.4

Fourth service: @DELETE (deletePlayerInfo())
URL:http://localhost:8080/ApacheCXF-Spring-Security/services/playerservice/deleteplayer
Request:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerType xmlns="http://benchresources.in/cdm/Player">
	<playerId>188</playerId>
	<name>Stephen Fleming</name>
	<age>41</age>
	<matches>111</matches>
</PlayerType>

Content-Type: application/xml
accept: application/x-www-form-urlencoded
Response: Player information deleted successfully
7_ApacheCXF-Spring-Security_playerservice_deleteplayer_xml

1.5

Fifth service: @GET (getAllPlayerInfo())
URL:http://localhost:8080/ApacheCXF-Spring-Security/services/playerservice/getallplayer
Request: None
Content-Type: application/x-www-form-urlencoded
accept: application/json
Response:

{
  "playerType": [
    {
      "playerId": 197,
      "name": "Nathan Astle",
      "age": 43,
      "matches": 83
    },
    {
      "playerId": 180,
      "name": "Dion Nash",
      "age": 43,
      "matches": 32
    }
  ]
}

8_ApacheCXF-Spring-Security_playerservice_getallplayer_json

 

2. Java Client

Uses HttpURLConnection and its supporting classes which comes shipped with JDK

Tested one service i.e.; /addplayer using HttpURLConnection and also provided authorization parameter to access the exposed service

Do test other services using this Java client making necessary changes to the requestParams[] array like requestURL, httpMethod, contentType, accept and include correct requestString

NOTE: Intentionally, commented out few lines of code to send/invoke request in JSON format

TestPlayerService.java

package test.apache.cxf.spring.security;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.MediaType;

import org.apache.commons.codec.binary.Base64;

public class TestPlayerService {

	/**
	 * main method to invoke test method
	 * @param args
	 */
	public static void main(String[] args) {

		String requestURL = "http://localhost:8080/ApacheCXF-Spring-Security/services/playerservice/addplayer";
		String httpMethod = HttpMethod.POST;
		String userName = "jeremy";
		String password = "jeremy123";
		String authString = userName + ":" + password;
		byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
		String authorization = new String(authEncBytes);
		String contentType = MediaType.APPLICATION_XML;
		String accept = MediaType.APPLICATION_FORM_URLENCODED;
		String requestString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
				+				"<PlayerType xmlns=\"http://benchresources.in/cdm/Player\">"
				+					"<playerId>188</playerId>"
				+					"<name>Stephen Fleming</name>"
				+					"<age>41</age>"
				+					"<matches>111</matches>"
				+ 				"</PlayerType>";

		String[] requestParams = {requestURL, httpMethod, authorization, contentType, accept, requestString};

		/*String requestURL = "http://localhost:8080/ApacheCXF-Spring-Security/services/playerservice/addplayer";
		String httpMethod = HttpMethod.POST;
		String userName = "jing";
		String password = "jing123";
		String authString = userName + ":" + password;
		byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
		String authorization = new String(authEncBytes);
		String contentType = MediaType.APPLICATION_JSON;
		String accept = MediaType.APPLICATION_FORM_URLENCODED;
		String requestString =  "{"
				+  		"\"playerId\": 188,"
				+  		"\"name\": \"Stephen Fleming\","
				+  		"\"age\": 41,"
				+  		"\"matches\": 111 "
				+  	"}";
		String[] requestParams = {requestURL, httpMethod, authorization, contentType, accept, requestString};*/

		String responseFromService = testPlayerService(requestParams);
		System.out.println("Response String: " + responseFromService);
	}

	/**
	 * This method uses HttpURLConnection to invoke exposed Restful web service and returns the response string to the calling client
	 * @param requestParams
	 * @return
	 */
	public static String testPlayerService(String[] requestParams) {

		// local variables
		URL url = null;
		HttpURLConnection httpURLConnection = null;
		OutputStreamWriter outputStreamWriter = null;
		String responseMessageFromServer = null;
		String responseXML = null; 

		try {
			url = new URL(requestParams[0]);
			httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setRequestMethod(requestParams[1]);
			httpURLConnection.setRequestProperty("Authorization", "Basic " + requestParams[2]);
			httpURLConnection.setRequestProperty("Content-Type", requestParams[3]);
			httpURLConnection.setRequestProperty("Accept", requestParams[4]);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setAllowUserInteraction(false);

			outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
			outputStreamWriter.write(requestParams[5]);
			outputStreamWriter.flush();

			System.out.println("Response code: " + httpURLConnection.getResponseCode());

			if (httpURLConnection.getResponseCode() == 200) {

				responseMessageFromServer = httpURLConnection.getResponseMessage();
				System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);
				responseXML = getResponseXML(httpURLConnection);
			}
		}
		catch(Exception  ex){
			ex.printStackTrace();
		}
		finally{
			httpURLConnection.disconnect();
		}
		return responseXML;
	}

	/**
	 * This method is used to get response XML from the HTTP GET Request created for Authorization WireKey
	 * @param httpURLConnection
	 * @return stringBuffer.toString()
	 * @throws IOException
	 */
	private static String getResponseXML(HttpURLConnection httpURLConnection) throws IOException{

		StringBuffer stringBuffer = new StringBuffer();
		BufferedReader bufferedReader = null;
		InputStreamReader inputStreamReader = null;
		String readSingleLine = null;

		try{
			// read the response stream AND buffer the result into a StringBuffer
			inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
			bufferedReader = new BufferedReader(inputStreamReader);

			// reading the XML response content line BY line
			while ((readSingleLine = bufferedReader.readLine()) != null) {
				stringBuffer.append(readSingleLine);
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		finally{
			// finally close all operations
			bufferedReader.close();
			httpURLConnection.disconnect();
		}
		return stringBuffer.toString();
	}
}

Output in Console

Response code: 200
ResponseMessageFromServer: OK
Response String: Player information saved successfully with PLAYER_ID 188

Study java client and do necessary changes to test other exposed services

Conclusion: With Spring-Security framework, we can protect the exposed web services and only authenticated & authorized users can access the services with correct credentials. Also, with hashing/encoding it’s a big advantage to protect the password

Download project

ApacheCXF-Spring-Security (11kB)

Happy Coding !!
Happy Learning !!

Apache CXF: JAX-RS Restful web service for uploading/downloading Text file + Java client
Apache CXF: JAX-RS Restful web service + Integrating with Spring & Hibernate