RestEasy: JAX-RS web service + Integrating with Spring Security

In this article, we will protect the RestEasy JAX-RS exposed web services using Spring Security. And only authorized users are allowed to access these protected services

JBoss RestEasy is a JAX-RS implementation for developing Restful web service in java. Once developed, it isn’t restricted to deploy only in JBoss Application Server but you can deploy in any other server like Apache Tomcat, Glassfish, Oracle Weblogic, etc

Annotation Used

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

Technology Used

  • Java 1.7
  • Eclipse Luna IDE
  • RestEasy-3.0.8.Final
  • Spring-webmvc-3.2.11.RELEASE
  • Spring-security-3.2.5.RELEASE
  • Apache Maven 3.2.1
  • Apache Tomcat 7.0.54
  • JBoss Application Server 7.1.1.Final
  • MySql-Connector-Java-5.1.32

Mavenize or download required jars

Add RestEasy-3.0.8.Final, Spring-3.2.11-Release, Spring-security-3.2.5-Release & MySql-Connector-Java-5.1.32 dependencies to pom.xml

	<properties>
		<resteasy.version>3.0.8.Final</resteasy.version>
		<resteasy.scope>compile</resteasy.scope> 			<!-- compile(Tomcat) / provided(JBoss) -->
		<spring.version>3.2.11.RELEASE</spring.version> 	<!-- 4.x doesn't work with RestEasy directly -->
		<spring.security.version>3.2.5.RELEASE</spring.security.version>
		<mysql.version>5.1.32</mysql.version>
		<compileSource>1.7</compileSource>
		<maven.compiler.target>1.7</maven.compiler.target>
		<maven.compiler.source>1.7</maven.compiler.source>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<!-- RESTEasy JAX RS Implementation -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jaxrs</artifactId>
			<version>${resteasy.version}</version>
			<scope>${resteasy.scope}</scope>
		</dependency>

		<!-- Resteasy Servlet Container Initializer -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-servlet-initializer</artifactId>
			<version>${resteasy.version}</version>
			<scope>${resteasy.scope}</scope>
		</dependency>

		<!-- Resteasy Jackson Provider -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jackson-provider</artifactId>
			<version>${resteasy.version}</version>
			<scope>${resteasy.scope}</scope>
		</dependency>

		<!-- Resteasy JAXB Provider -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jaxb-provider</artifactId>
			<version>${resteasy.version}</version>
			<scope>${resteasy.scope}</scope>
		</dependency>

		<!-- RESTEasy JAX RS Client -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-client</artifactId>
			<version>${resteasy.version}</version>
			<scope>${resteasy.scope}</scope>
		</dependency>

		<!-- Resteasy Spring Integration -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-spring</artifactId>
			<version>${resteasy.version}</version>
			<exclusions>
				<exclusion>
					<artifactId>commons-logging</artifactId>
					<groupId>commons-logging</groupId>
				</exclusion>
				<exclusion>
					<artifactId>jaxb-impl</artifactId>
					<groupId>com.sun.xml.bind</groupId>
				</exclusion>
				<exclusion>
					<artifactId>sjsxp</artifactId>
					<groupId>com.sun.xml.stream</groupId>
				</exclusion>
				<exclusion>
					<artifactId>jsr250-api</artifactId>
					<groupId>javax.annotation</groupId>
				</exclusion>
				<exclusion>
					<artifactId>activation</artifactId>
					<groupId>javax.activation</groupId>
				</exclusion>
			</exclusions>
		</dependency>

		<!-- Spring Framework-3.2.x -->
		<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-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Spring Security 3.2.5.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>

		<!-- MySql-Connector -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.version}</version>
		</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 central repository or maven repository and download directly from Spring site 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.6</version>
	<executions>
		<execution>
			<goals>
				<goal>xjc</goal><!-- xjc/generate -->
			</goals>
			<configuration>
				<outputDirectory>${basedir}/generated/java/source</outputDirectory>
				<schemaDirectory>${basedir}/src/main/resources/com/resteasy/series/spring/security/service/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>

Customer.xsd

Below XSD contains two elements with name “CustomerType” and “CustomerListType”

  • CustomerType contains three attributes namely customerId, name, age
  • CustomerListType which returns list of CustomerType
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	targetNamespace="http://benchresources.in/cdm/Customer" xmlns:tns="http://benchresources.in/cdm/Customer"
	elementFormDefault="qualified">

	<!-- player object with three attributes -->
	<xsd:element name="CustomerType">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element name="customerId" type="xsd:int" />
				<xsd:element name="name" type="xsd:string" />
				<xsd:element name="age" type="xsd:int" />
			</xsd:sequence>
		</xsd:complexType>
	</xsd:element>

	<!-- an object to contain lists of players referencing above player object -->
	<xsd:element name="CustomerListType">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element ref="tns:CustomerType" 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

CustomerType.java

package in.benchresources.cdm.customer;

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 = {
    "customerId",
    "name",
    "age"
})
@XmlRootElement(name = "CustomerType")
public class CustomerType {

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

    public int getCustomerId() {
        return customerId;
    }

    public void setCustomerId(int value) {
        this.customerId = 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;
    }
}

CustomerListType.java

package in.benchresources.cdm.customer;

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 = {
    "customerType"
})
@XmlRootElement(name = "CustomerListType")
public class CustomerListType {

    @XmlElement(name = "CustomerType")
    protected List<CustomerType> customerType;

    public List<CustomerType> getCustomerType() {
        if (customerType == null) {
            customerType = new ArrayList<CustomerType>();
        }
        return this.customerType;
    }
}

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
  • src/test/resources –> all test related configuration files 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_RestEasy-Spring-Security_Project_Structure_In_Eclipse

Jars Libraries Used in the Project (Maven Dependencies)

2_RestEasy-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 RestEasy JAX-RS Restful web service

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

This web.xml file describes,

  • register RestEasy Bootstrap listener jboss.resteasy.plugins.server.servlet.ResteasyBootstrap and this should be at the top among all listeners
  • register another listener jboss.resteasy.plugins.spring.SpringContextLoaderListener
  • Like any JEE web framework register jboss.resteasy.plugins.server.servlet.HttpServletDispatcher with servlet container
  • http requests with URL pattern “/resteasy/*” will be sent to the registered servlet called “ws.rs.core.Application” i.e.; HttpServletDispatcher (org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher)
  • set servlet.mapping.prefix as <context-param>, if your servlet-mapping has a url-pattern anything other than “/*”. In this example, set “/resteasy”
  • if not set, then you will end up with 404 not found error
  • <context-param> with its attributes describes the location of the “spring-resteasy.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>RestEasy-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>

	<!-- RestEasy Bootstrap -->
	<listener>
		<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
	</listener>

	<!-- Spring Bootstrap -->
	<listener>
		<listener-class>org.jboss.resteasy.plugins.spring.SpringContextLoaderListener</listener-class>
	</listener>

	<!-- RestEasy Servlet -->
	<servlet>
		<servlet-name>javax.ws.rs.core.Application</servlet-name>
		<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>javax.ws.rs.core.Application</servlet-name>
		<url-pattern>/resteasy/*</url-pattern>
	</servlet-mapping>

	<!-- loading Spring Context for registering beans with ApplicationContext -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			WEB-INF/spring-resteasy.xml,
			WEB-INF/spring-security.xml
		</param-value>
	</context-param>

	<!-- this is mandatory, if url-pattern is other than /* -->
	<context-param>
		<param-name>resteasy.servlet.mapping.prefix</param-name>
		<param-value>/resteasy</param-value>
	</context-param>

	<!-- welcome file -->
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>

</web-app>

Spring Application Context file

This Spring Application Context file 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

spring-resteasy.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:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

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

	<!-- scans packages to find and register beans within the application context -->
	<context:component-scan base-package="com.resteasy.series.spring.security" />

	<!-- 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.resteasy.series.spring.security.hashing;

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(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 user credentials along with their ROLES, interacting with dataSource configured in the spring-resteasy.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="/resteasy/**"
			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>/<root-context>/<from_here_application_specific_path>

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

We have configured “/resteasy/*” as url-pattern for the “javax.ws.rs.core.Application” servlet in web.xml and at interface-level (or say class-level) path configured is “/customerservice” using @Path annotation. Next respective path for each method annotated with @Path (method-level)

Customer Service interface

 Defines simple CURD operations

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

Let’s discuss @Produces, @Consumes and MediaType

@Consumes
Defines 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
Defines 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_HTML,
  • 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

ICustomerService.java

package com.resteasy.series.spring.security.service;

import in.benchresources.cdm.customer.CustomerListType;
import in.benchresources.cdm.customer.CustomerType;

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("/customerservice")
public interface ICustomerService {

	// Basic CRUD operations for Customer Service

	// http://localhost:8080/RestEasy-Spring-Security/resteasy/customerservice/addcustomer  - Tomcat 7.0.x
	// http://localhost:9090/RestEasy-Spring-Security/resteasy/customerservice/addcustomer  - JBoss AS7
	@POST
	@Path("addcustomer")
	@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	@Produces({MediaType.APPLICATION_FORM_URLENCODED})
	public String createOrSaveNewCustomerInfo(CustomerType customerType);

	// http://localhost:8080/RestEasy-Spring-Security/resteasy/customerservice/getcustomer/10001  - Tomcat 7.0.x
	// http://localhost:9090/RestEasy-Spring-Security/resteasy/customerservice/getcustomer/10001  - JBoss AS7
	@GET
	@Path("getcustomer/{id}")
	@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public CustomerType getCustomerInfo(@PathParam("id") int customerId);

	// http://localhost:8080/RestEasy-Spring-Security/resteasy/customerservice/updatecustomer  - Tomcat 7.0.x
	// http://localhost:9090/RestEasy-Spring-Security/resteasy/customerservice/updatecustomer  - JBoss AS7
	@PUT
	@Path("updatecustomer")
	@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	@Produces({MediaType.APPLICATION_FORM_URLENCODED})
	public String updateCustomerInfo(CustomerType Customer);

	// http://localhost:8080/RestEasy-Spring-Security/resteasy/customerservice/deletecustomer  - Tomcat 7.0.x
	// http://localhost:9090/RestEasy-Spring-Security/resteasy/customerservice/deletecustomer  - JBoss AS7
	@DELETE
	@Path("deletecustomer")
	@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	@Produces({MediaType.APPLICATION_FORM_URLENCODED})
	public String deleteCustomerInfo(CustomerType Customer);

	// http://localhost:8080/RestEasy-Spring-Security/resteasy/customerservice/getallcustomer  - Tomcat 7.0.x
	// http://localhost:9090/RestEasy-Spring-Security/resteasy/customerservice/getallcustomer  - JBoss AS7
	@GET
	@Path("getallcustomer")
	@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public CustomerListType getAllCustomerInfo();
}

Customer Service implementation

Implements above interface. JAX-RS classes should be annotated with Spring annotation like @Component or @Service

CustomerServiceImpl.java

package com.resteasy.series.spring.security.service;

import org.springframework.stereotype.Component;

import in.benchresources.cdm.customer.CustomerListType;
import in.benchresources.cdm.customer.CustomerType;

@Component
public class CustomerServiceImpl implements ICustomerService {

	/**
	 * returns a String value with SUCCESS message after adding/saving a New Customer information
	 */
	@Override
	public String createOrSaveNewCustomerInfo(CustomerType customerType) {

		// get the player information from formal arguments and inserts into database & return playerId (primary_key)
		return "Customer information saved successfully with Customer_ID " + customerType.getCustomerId();
	}

	/**
	 * retrieves a customer information object based on the ID supplied in the formal argument using @PathParam
	 */
	@Override
	public CustomerType getCustomerInfo(int customerId) {

		// retrieve player based on the id supplied in the formal argument
		CustomerType customerType = new CustomerType();
		customerType.setCustomerId(customerId);
		customerType.setName("Captain Planet");
		customerType.setAge(40);
		return customerType;
	}

	/**
	 * returns a String value with SUCCESS message after updating customer information
	 */
	@Override
	public String updateCustomerInfo(CustomerType customerType) {

		// update customer info & return SUCCESS message
		return "Customer information updated successfully";
	}

	/**
	 * returns a String value with SUCCESS message after deleting customer information
	 */
	@Override
	public String deleteCustomerInfo(CustomerType customerType) {

		// delete customer info & return SUCCESS message
		return "Customer information deleted successfully";
	}

	/**
	 * retrieves all customer stored
	 */
	@Override
	public CustomerListType getAllCustomerInfo() {

		// create a object of type CustomerListType which takes customer objects in its list
		CustomerListType customerListType = new CustomerListType();

		CustomerType customerOne = new CustomerType();
		customerOne.setCustomerId(10025);
		customerOne.setName("Super Man");
		customerOne.setAge(37);
		customerListType.getCustomerType().add(customerOne); // add to customerListType

		CustomerType customerTwo = new CustomerType();
		customerTwo.setCustomerId(10026);
		customerTwo.setName("Batman");
		customerTwo.setAge(33);
		customerListType.getCustomerType().add(customerTwo); // add to customerListType

		return customerListType;
	}
}

 

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 the URL of GET service into web browser
  • Advanced REST client from Google Chrome
  • Rest client in Mozilla Firefox Add On
  • Write your own client for example, Java client using improved CloseableHttpClient from Apache
  • JDK’s in-built classes like HttpURLConnection
  • Using Client, WebTarget from core JAX-RS classes javax.ws.rs.client
  • Using ResteasyClient, ResteasyWebTarget and Response classes from JBoss package org.jboss.resteasy.client
  • Using ClientRequest and ClientResponse classes from JBoss package org.jboss.resteasy.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 “/resteasy/**”. See spring-security.xml file for details

3_RestEasy-Spring-Security_basic_authentication

getAllCustomer() service

4_RestEasy-Spring-Security_get_all_customers_json

Similarly, we can test other exposed services using Mozilla Rest client

 

2. Java client (RestEasy)

There are two test clients which comes from JBoss RestEasy package org.jboss.resteasy.client and org.jboss.resteasy.client.jaxrs

  1. ClientRequest and ClientResponse for invoking getCustomerInfo service
  2. ResteasyClient, ResteasyClientBuilder and ResteasyWebTarget for invoking addCustomerInfo service

Self-explanatory !!

Note: above clients can be interchanged. No restriction, only needs to set correct http request parameters or header values

TestCustomerService.java

package test.resteasy.series.spring.security.service;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.codec.binary.Base64;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

public class TestCustomerService {

	public static void main(String[] args) throws Exception {

		// encoding with Base64 and passing as authorization
		String userName = "jeremy";
		String password = "jeremy123";
		String authString = userName + ":" + password;
		byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
		String authorization = new String(authEncBytes);

		// setting & invoking first service getCustomer/45001
		System.out.println("Invoking and executing getCustomer service for customer id 45001");
		String httpGetURL = "http://localhost:8080/RestEasy-Spring-Security/resteasy/customerservice/getcustomer/45001";
		String responseStringGet = testCustomerServiceForGetRequest(httpGetURL, authorization);
		System.out.println("GET >> Response String : " + responseStringGet);

		// setting & invoking second service addCustomer with XML/JSON request
		System.out.println("\n\nInvoking and executing addCustomer service with request");
		String httpPostURL = "http://localhost:8080/RestEasy-Spring-Security/resteasy/customerservice/addcustomer";
		String requestStringInXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
				+ 					"<CustomerType xmlns=\"http://benchresources.in/cdm/Customer\">"
				+ 						"<customerId>45021</customerId>"
				+ 						"<name>Nobita</name>"
				+ 						"<age>26</age>"
				+ 					"</CustomerType>";
		String responseStringPost = testCustomerServiceForPostRequest(httpPostURL, authorization, requestStringInXML);
		System.out.println("POST >> Response String : " + responseStringPost);
	}

	/**
	 * using ClientRequest and ClientResponse classes from org.jboss.resteasy.client
	 * @param httpURL
	 * @return responseString
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public static String testCustomerServiceForGetRequest(String httpURL, String authorization) throws Exception {

		// local variables
		ClientRequest clientRequest = null;
		ClientResponse<String> clientResponse = null;
		int responseCode;
		String responseMessageFromServer = null;
		String responseString = null;

		try{
			// invoke service after setting necessary parameters
			clientRequest = new ClientRequest(httpURL);
			clientRequest.setHttpMethod(HttpMethod.GET);
			clientRequest.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED); 	// set Content-Type
			clientRequest.header("Authorization", "Basic " + authorization); 				// authorization using BCrpyt
			clientRequest.accept(MediaType.APPLICATION_XML); 								// set accept
			clientResponse = clientRequest.get(String.class);

			// get response code
			responseCode = clientResponse.getResponseStatus().getStatusCode();
			System.out.println("Response code: " + responseCode);

			if(clientResponse.getResponseStatus().getStatusCode() != 200) {
				throw new RuntimeException("Failed with HTTP error code : " + responseCode);
			}

			// get response message
			responseMessageFromServer = clientResponse.getResponseStatus().getReasonPhrase();
			System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);

			// get response string
			responseString = clientResponse.getEntity();
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
		finally{
			// release resources, if any
			clientResponse.close();
			clientRequest.clear();
		}
		return responseString;
	}

	/**
	 * using ResteasyClient, ResteasyWebTarget and Response classes from org.jboss.resteasy.client
	 * @param httpURL
	 * @param requestString
	 * @return
	 */
	public static String testCustomerServiceForPostRequest(String httpURL, String authorization, String requestString)  throws Exception {

		// local variables
		ResteasyClient resteasyClient = null;
		ResteasyWebTarget resteasyWebTarget = null;
		Response response = null;
		int responseCode;
		String responseMessageFromServer = null;
		String responseString = null;

		try{
			// invoke service after setting necessary parameters
			resteasyClient = new ResteasyClientBuilder().build();
			resteasyWebTarget = resteasyClient.target(httpURL);
			response = resteasyWebTarget
					.request(MediaType.APPLICATION_FORM_URLENCODED)						// set Content-Type
					.header("Authorization", "Basic " + authorization)					// authorization using BCrpyt
					.post(Entity.entity(requestString, MediaType.APPLICATION_XML));		// set accept 

			// get response code
			responseCode = response.getStatus();
			System.out.println("Response code: " + responseCode);

			if (response.getStatus() != 200) {
				throw new RuntimeException("Failed with HTTP error code : " + responseCode);
			}

			// get response message
			responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
			System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);

			// read response string
			responseString = response.readEntity(String.class);
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		finally{
			// release resources, if any
			response.close();
		}
		return responseString;
	}
}

Output in console

Invoking and executing getCustomer service for customer id 45001
Response code: 200
ResponseMessageFromServer: OK
GET >> Response String : 
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<CustomerType xmlns="http://benchresources.in/cdm/Customer">
	<customerId>45001</customerId>
	<name>Captain Planet</name>
	<age>40</age>
</CustomerType>


Invoking and executing addCustomer service with request
Response code: 200
ResponseMessageFromServer: OK
POST >> Response String : Customer information saved successfully with Customer_ID 45021

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

Download project (Tomcat Server 7.0.x)

RestEasy-Spring-Security (Tomcat server) (16kB)

 

JBoss Deployment

  1. Update pom.xml with resteasy scope “provided” for dependencies as JBoss AS7 modules already contains these dependent jars
    <resteasy.scope>provided</resteasy.scope> <!-- compile(Tomcat) / provided(JBoss) -->
    
  2. Update web.xml
    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>RestEasy-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>
    
    	<!-- RestEasy Bootstrap -->
    	<listener>
    		<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
    	</listener>
    
    	<!-- Spring Bootstrap -->
    	<listener>
    		<listener-class>org.jboss.resteasy.plugins.spring.SpringContextLoaderListener</listener-class>
    	</listener>
    
    	<!-- RestEasy Servlet -->
    	<servlet-mapping>
    		<servlet-name>javax.ws.rs.core.Application</servlet-name>
    		<url-pattern>/resteasy/*</url-pattern>
    	</servlet-mapping>
    
    	<!-- loading Spring Context for registering beans with ApplicationContext -->
    	<context-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>
    			WEB-INF/spring-resteasy.xml,
    			WEB-INF/spring-security.xml
    		</param-value>
    	</context-param>
    
    	<!-- welcome file -->
    	<welcome-file-list>
    		<welcome-file>index.html</welcome-file>
    	</welcome-file-list>
    </web-app>
    
  3. Rest remain the same
  4. Read through this article which explains development & deployment of RestEasy web service with JBoss Application Server in detail

Note: JBoss Application Server 7.1.1.Final comes with default RestEasy distribution with version 2.3.2.Final. So update JBoss AS7 with latest RestEasy version. Look at this article, which explains how to update default version with latest version available in the JBoss community

Download project (JBoss Application Server 7.1.1.Final)

RestEasy-Spring-Security (JBoss server) (16kB)

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

Happy Coding !!
Happy Learning !!

RestEasy: JAX-RS web service for uploading/downloading Text file + Java client
RestEasy: JAX-RS web service + Integrating with Spring MVC and Hibernate ORM framework