RSS

Category Archives: Other

SSL configuration on spring boot application with self signed certificate


Let’s start with What?

SSL – (Secure Sockets Layer) is the standard security technology for establishing an encrypted link between a web server and a browser. This link ensures that all data passed between the web server and browsers remain private and integral

Self signed certificate – is an identity certificate that is signed by the same entity whose identity it certifies

Keystore and Truststore – is used to store SSL certificates in Java but there is subtle difference between them. truststore is used to store public certificates while keystore is used to store private certificates of client or server

Let’s pretend you need to build simple application with spring boot(with fat jar deployment) and you need to expose the application with encryption(over https). In oder to do that you have to configure the spring boot application over https by adding the key-store which holds the certificates. So when its comes to get the certificate you have to choices either self signed or signed by one of the public certificate authorities(CAs)

Now the question is why we need to go for the self signed certificate rather public CA signed certificate. The main reason that people do self-signed certificates because it doesn’t add any cost it is free, But if the site is public facing it would be better to go for the public CA signed certificate rather the self signed. So if you have public CA signed certificate then client browser do verify the certificate without any problem because the browser by default identifies the public CAs otherwise it will show as follows which is not trusted site unless you import the certificate to the browser trust store.

screen-shot-2017-01-28-at-10-10-56-am

The good thing is you will get the encryption over https no matter which certificate you use.

Best scenario that I’m thinking is to create a self-signed certificate when you are in DEV and TEST environments but when you need to expose that to PROD which will be exposing to public use the public CA signed certificate. But if it is internal facing then you can still use the self-signed certificate once you have registered the certificate on clients browser trust stores.

How to create the self signed certificate with JAVA key-tool.

1. Create Java Key Store with certificate

keytool -genkey -keyalg RSA -alias selfsigned -keystore ${DEST_PATH}/keystore.jks -storepass ${PASS_WORD} -validity 360 -keysize 2048

screen-shot-2017-01-28-at-10-54-29-am

2. List out the details of the given keystore 

keytool -v -list -keystore ${PATH_TO_KEYSTORE}/keystore.jks

Screen Shot 2017-01-28 at 11.03.51 AM.png

3. Export self-signed certificate if you want to distribute to the clients.

keytool -exportcert -rfc -alias selfsigned -keystore ${DEST_PATH}/keystore.jks -file ${DEST_PATH}/selfsigned.crt

Screen Shot 2017-01-28 at 10.59.21 AM.png

4. Verify the certificate

keytool -printcert -file ${PATH_TO_CERTIFCATE}/selfsigned.crt

Screen Shot 2017-01-28 at 11.12.26 AM.png

So now need to expose your .jks file to spring boot application and configure that to be exposed as https. Fist of all place your keystore.jks file on the class path and then set the following properties in application-*.properties file.

server.port=8443
server.ssl.key-alias=selfsigned
server.ssl.key-password=test123
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS

 

 
4 Comments

Posted by on January 28, 2017 in java, Other, spring

 

Tags: , , , , ,

How to make the java runtime to trust the certificate present by the host


URL -https://my-site.com/test

Let’s start with simple example. If you invoke above URL through your simple java application you will simply get the SSLHandshakeException because it is exposed as https endpoint and the java runtime is not going to trust the certificate that present through the URL call. So before you invoke the service you have to present the certificate to your java runtime to trust the certificate. Then when ever you call the URL it will trust the certificate. You can do this in two different ways as follows.

  1. Download and import the certificate to your java runtime certificate store.
  2. Write the code in your program to trust the certificate provided by the host.

1. Download and import the certificate to your java runtime certificate store.

First of all you have to download the certificate from the host. In order to do that you can simply go to the URL through the browser and then download the certificate to your local machine as .cer file.

In Chrome browser you can simply go to the certificate as follows and drag and drop to the local folder. I choose the https://google.com as a example.

1

2

So once you have downloaded the certificate  you should be able to use the keytool to import the certificate.

keytool -import -alias google -keystore ${PATH_TO_JDK}/jre/lib/security/cacerts -file ${PATH_TO_CERT_FILE}

You have to provide the keystore password as “changeit” unless you have customized it.

ex/

keytool -import -alias google -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/jre/lib/security/cacerts -file /Users/dmalalan/Documents/www.google.com.cer

3

screen-shot-2017-01-14-at-11-48-44-am

2. Write the code in your program to trust the certificate provided by the host

You need to use the following code sample before you invoke the URL. This is just allow the runtime to trust all the certificates presented by the host but you need to be careful with this approach because host can present the bogus certificates.

screen-shot-2017-01-14-at-11-55-53-am

References : sample code & sample instructions

 
Leave a comment

Posted by on January 14, 2017 in java, Other, web

 

Tags: , , ,

Comparator and Comparable interfaces in Java


c4c3

Comparator and Comparable interfaces are heavily used in the Java development to manage the sorting of the collections. This approach will achieve the software engineering goals such as extensibility, reusability, modularity etc. In this post I like to explain this mechanism of how to use comparator and comparable interfaces. First thing is we are going to use the Collections API for sorting which is provided by Java. So we have to expose sorting comparison logic without exposing the internal structure of our custom implementation.Here you can download the source.

Lets look at how to use Comparable interface.

As an example I have Employee class which is created by me and need to sort the collection of employees according to the employee age.

  • First we need to implement the Comparable interface in Employee class and override the compareTo method
  • Then we can pass the employee collection to the Collections.sort() API to do the sorting.
  • Underneath what will happen Collections.sort() method will access the compareTo implementation and get the decision according to the return value.

See the code sample below to get clear understanding.

package sample.common;

/**
 * Employee Class
 *
 * @author malalanayake
 *
 */
public class Employee implements Comparable<Employee> {
	private int id;
	private String name;
	private int age;
	private int salary;

	public Employee(int id, String name, int age, int salary) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.salary = salary;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

	public int compareTo(Employee o) {
		if (o.getAge() == this.age) {
			return 0;
		} else if (o.getAge() > this.age) {
			return -1;
		} else {
			return 1;
		}
	}

	@Override
	public String toString() {
		return "[Employee ID:" + this.getId() + " Name:" + this.getName()
				+ " Age:" + this.getAge() + " Salary:" + this.getSalary() + "]";
	}

}
package sample.app;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import comparator.sample.app.SalaryComparator;
import sample.common.Employee;

/**
 * Application Class
 *
 * @author malalanayake
 *
 */
public class App {
	public static void main(String[] args) {
		List<Employee> employees = new ArrayList<Employee>();

		Employee emp_dinuka = new Employee(101, "Dinuka", 27, 95000);
		employees.add(emp_dinuka);

		Employee emp_malalanayake = new Employee(100, "Malalanayake", 27, 85000);
		employees.add(emp_malalanayake);

		Employee emp_Thanuja = new Employee(305, "Thanuja", 23, 150000);
		employees.add(emp_Thanuja);

		Employee emp_Damith = new Employee(204, "Damith", 20, 75000);
		employees.add(emp_Damith);

		System.out.println("=======Before Sorting=====");
		for (Employee emp : employees) {
			System.out.println(emp.toString());
		}

		Collections.sort(employees);
		System.out.println("=======After Sorting=====");
		for (Employee emp : employees) {
			System.out.println(emp.toString());
		}
	}
}

You can see in the above case we can have only one sorting logic over the employee class. Lets think about sometimes if I need to sort the Employee by their salaries and sometimes I need to sort by their age. Then you can see we don’t have space to put that logic in my Employee class because already I have method implementation according to the age. In this kind of situation Comparator comes to the picture to solve the problem.

Lets look at how to use Comparator

  • So first you have to have comparator implementation class. In above case I have created SalaryComparator class which is provide the salary comparison.
  • Then you can pass the employee collection to overloaded method in collections api to sort the given collection according to the given comparator.
package comparator.sample.app;

import java.util.Comparator;

import sample.common.Employee;

/**
 * Salary Comparator
 *
 * @author malalanayake
 *
 */
public class SalaryComparator implements Comparator<Employee> {

	public int compare(Employee o1, Employee o2) {
		if (o1.getSalary() > o2.getSalary()) {
			return 1;
		}

		if (o1.getSalary() < o2.getSalary()) {
			return -1;
		}
		return 0;
	}

}
package sample.app;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import comparator.sample.app.SalaryComparator;
import sample.common.Employee;

/**
 * Application Class
 *
 * @author malalanayake
 *
 */
public class App {
	public static void main(String[] args) {
		List<Employee> employees = new ArrayList<Employee>();

		Employee emp_dinuka = new Employee(101, "Dinuka", 27, 95000);
		employees.add(emp_dinuka);

		Employee emp_malalanayake = new Employee(100, "Malalanayake", 27, 85000);
		employees.add(emp_malalanayake);

		Employee emp_Thanuja = new Employee(305, "Thanuja", 23, 150000);
		employees.add(emp_Thanuja);

		Employee emp_Damith = new Employee(204, "Damith", 20, 75000);
		employees.add(emp_Damith);

		SalaryComparator comparator = new SalaryComparator();
		Collections.sort(employees, comparator);
		System.out.println("=======After Sorting By Salary=====");
		for (Employee emp : employees) {
			System.out.println(emp.toString());
		}
	}
}

So If you have multiple sorting logics then you have to go for the Comparator because then only you can have multiple logics. Otherwise you can encapsulate the logic inside your custom implementation class by using the Comparable interface. I hope you got the idea of how to use the comparator and comparable interfaces.

 
Leave a comment

Posted by on December 5, 2014 in java, Other

 

Tags: , , , ,

Selecting proper data structures for the realtime problems


As a software engineer you have to have a proper understanding about data structures and the corresponding implementations. In real world application development you need to think about the efficiency of the operations and it should fit for the entire domain that the solution is addressing. So in this blog post Im going to explain some of the data structures implemented in java.

Look at the following class hierarchy.

collections

1. LinkedList –  Use the linked list If you need to maintain the list which is no need random access to the values and needed frequent insertions and deletions.
Insertion and deletion is O(1) and access the (k)th element is O(n).
But remember LinkedList is not thread safe.

2. ArrayList –  Use the array list if you need the random access to the values frequently and same as you don’t need frequent insertion and remove operations.
Access the (k)th element is O(1) and insertion and deletion is O(n).
Same as LinkedList remember ArrayList is not thread safe.

3. Vector –  When you need to maintain thread safety over the ArrayList use the Vector. If you don’t need any synchronization on each and every operations you have to go for ArrayList otherwise it will give bad performance impact on each operation.

4. PriorityQueue –  We know that queue is a first come first serve basis but some times we need to get the things according to the priority. So if you have that kind of problem use the priority queue. But remember PriorityQueue is not thread safe.

5. HashSet –  It is not maintaining the duplicates. When you need to maintain the unique list of objects you can use the HashSet. HashSet allows the NULL Objects but it is not maintain the insertion sequence. If you need to maintain the insertion sequence you have to use the LinkedHashSet.

6. TreeSet –  Same as HashSet this data structure maintain the duplicate free collection and additionally its provide the sorted order of the elements.TreeSet is not allow the NULL objects. Guarantees log(n) time cost for the basic operations add, remove and contains.

7. HashTable –  This data structure is useful when you need to do the insertion, deletion and the quick access to the given element in constant time. All operations are in O(1).Hash tables are not maintain the insertion sequence. I would like to explain the HashTable little bit in depth because this is commonly using in the industry. As an example a router table. When a packet has to be routed to a specific IP address, the router has to determine the best route by querying the router table in an efficient manner.

To use the Hash tables you have to implement the equals(), hashCode() functions the Object type that you are going to store in the HashTable.
hashCode() – as a best practice you have to consider all attributes in the object to generate the hash code. See the following example.

public class Employee {
    int        employeeId;
    String     name;
    Department dept;
 
    // other methods would be in here 
 
    @Override
    public int hashCode() {
        int hash = 1;
        hash = hash * 17 + employeeId;
        hash = hash * 31 + name.hashCode();
        hash = hash * 13 + (dept == null ? 0 : dept.hashCode());
        return hash;
    }
}

Once you call the insert method in the hash table it will calculate the hash value and then store the the data according to the hash value.

 int hashValue = hashCode % hash_table_size;

There are several ways to handle the collisions in hash table.
1. Separate Chaining – Maintain the list in each slot. If there are two objects with same hash value it is going to store in that list. This implementation has extra overhead to maintain the list. Total Performance is depend on the number of elements in the list.

2. Open Addressing – In this approach it is find the next available slot according to the probing function.
Linear prob – h(x), h(x)+1, h(x)+2, h(x)+3,..
Quadratic prob – h(x), h(x)+1^2, h(x)+2^2, h(x)+3^2,..
Double hashing – h(x), h(x)+1*h'(x), h(x)+2*h'(x), h(x)+3*h'(x),..

Delete elements in hash table – If hash table is use open addressing then it is logically delete the value from the table by setting a flag.

Performance of the hash table is denoted by alpha load factor.

 alpha = number_of_elements/table_size;

If hash table is filled we need to do the rehashing. Rehashing is done according to the load factor. If load factor reaches to some level we need to do the rehashing. This is the only disadvantage of the HashTable.

8. HashMap –  Hash map is used when you need to store the elements as key, value pairs.In hash map you cannot duplicate the key but you can duplicate the value with different key. This is not maintain the insertion sequence. If you need to maintain the insertion sequence you have to use the LinkedHashMap. Remember HasMap is not thread safe if you need thread safety over HashMap you have to use the ConcurrentHashMap

8. TreeMap –  If you need to maintain the key, value pairs in sorted order this is the data structure suits for that operation. Its guarantees that the given key value pairs arrange in sorted order according to the compareTo() method in Object type which is stored in TreeMap.

 
Leave a comment

Posted by on September 26, 2014 in data-structures, java, Other

 

Tags: , ,

Spring Security on REST API


I think this post will be good who are working in REST api development. If you are in trouble with the security on REST api this will be really helpful to solve the problems.

Screen Shot 2014-06-26 at 5.09.07 PM

In above project structure I would like to explain the web.xml configuration as follows.

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

	<display-name>Spring MVC Application</display-name>
        <session-config>
		<session-timeout>1</session-timeout>
	</session-config>

	<!-- Spring root -->
	<context-param>
		<param-name>contextClass</param-name>
		<param-value>
         org.springframework.web.context.support.AnnotationConfigWebApplicationContext
      </param-value>
	</context-param>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>spring.security.rest.api</param-value>
	</context-param>

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

	<!-- Spring child -->
	<servlet>
		<servlet-name>api</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>api</servlet-name>
		<url-pattern>/api/*</url-pattern>
	</servlet-mapping>

	<!-- 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>
	</filter-mapping>

</web-app>

1. Define the spring root configuration.

<!-- Spring root -->
	<context-param>
		<param-name>contextClass</param-name>
		<param-value>
         org.springframework.web.context.support.AnnotationConfigWebApplicationContext
      </param-value>
	</context-param>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>spring.security.rest.api</param-value>
	</context-param>

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

In the above code snippet you can see I have define the “contextConfigLocation” parameter which is pointing the “spring.security.rest.api” this would be the initialization point of configuration. So you have to make sure you give the correct package name where the spring configuration is located.

2. Servlet mapping configuration

<!-- Spring child -->
	<servlet>
		<servlet-name>api</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>api</servlet-name>
		<url-pattern>/api/*</url-pattern>
	</servlet-mapping>

This is the point that you have to manage your url. you can give what you want as a url and it will expose the defined apis followed by the above url.
ex/ http://localhost:8080/spring.security.rest.api/api/customer

3. Spring security configuration

<!-- 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>
	</filter-mapping>

you need to exactly define the filter-name as “springSecurityFilterChain” and as a good practice we are defining the url pattern as “/*” even our api starts at “/api/*” because then we can control the whole domain when its required.

Now I would like to go for the most important part of this project that is Spring security configuration. Lets see the webSecurityConfig.xml which is located at class path.

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

	<!-- Rest authentication entry point configuration -->
	<http use-expressions="true" entry-point-ref="restAuthenticationEntryPoint">
		<intercept-url pattern="/api/**" />
		<sec:form-login authentication-success-handler-ref="mySuccessHandler"
			authentication-failure-handler-ref="myFailureHandler" />

		<logout />
	</http>

	<!-- Connect the custom authentication success handler -->
	<beans:bean id="mySuccessHandler"
		class="spring.security.rest.api.security.RestAuthenticationSuccessHandler" />
	<!-- Using default failure handler -->
	<beans:bean id="myFailureHandler"
		class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler" />

	<!-- Authentication manager -->
	<authentication-manager alias="authenticationManager">
		<authentication-provider>
			<user-service>
				<user name="temporary" password="temporary" authorities="ROLE_ADMIN" />
				<user name="user" password="userPass" authorities="ROLE_USER" />
			</user-service>
		</authentication-provider>
	</authentication-manager>

	<!-- Enable the annotations for defining the secure role -->
	<global-method-security secured-annotations="enabled" />

</beans:beans>

In the above xml file I have defined the entry point as “restAuthenticationEntryPoint” with the success and failure handler what it means, in the spring context entry point is used to redirect the non authenticated request to get the authentication. In REST Api point of view this entry point is doesn’t make sense. As an example If the request comes without the authentication cookie application is not going to redirect the request to get the authentication rather sending the response as 401 Unauthorized.

package spring.security.rest.api.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;

/**
 * This will call once the request is authenticated. If it is not, the request
 * will be redirected to authenticate entry point
 * 
 * @author malalanayake
 * 
 */
public class RestAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
	private RequestCache requestCache = new HttpSessionRequestCache();

	@Override
	public void onAuthenticationSuccess(final HttpServletRequest request,
			final HttpServletResponse response, final Authentication authentication)
			throws ServletException, IOException {
		final SavedRequest savedRequest = requestCache.getRequest(request, response);

		if (savedRequest == null) {
			clearAuthenticationAttributes(request);
			return;
		}
		final String targetUrlParameter = getTargetUrlParameter();
		if (isAlwaysUseDefaultTargetUrl()
				|| (targetUrlParameter != null && StringUtils.hasText(request
						.getParameter(targetUrlParameter)))) {
			requestCache.removeRequest(request, response);
			clearAuthenticationAttributes(request);
			return;
		}

		clearAuthenticationAttributes(request);

		// Use the DefaultSavedRequest URL
		// final String targetUrl = savedRequest.getRedirectUrl();
		// logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
		// getRedirectStrategy().sendRedirect(request, response, targetUrl);
	}

	public void setRequestCache(final RequestCache requestCache) {
		this.requestCache = requestCache;
	}
}
package spring.security.rest.api.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

/**
 * This entry point is called once the request missing the authentication but if
 * the request dosn't have the cookie then we send the unauthorized response.
 * 
 * @author malalanayake
 * 
 */
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest arg0, HttpServletResponse arg1,
			AuthenticationException arg2) throws IOException, ServletException {
		arg1.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");

	}

}

Spring-Security

<!-- Authentication manager -->
	<authentication-manager alias="authenticationManager">
		<authentication-provider>
			<user-service>
				<user name="temporary" password="temporary" authorities="ROLE_ADMIN" />
				<user name="user" password="userPass" authorities="ROLE_USER" />
			</user-service>
		</authentication-provider>
	</authentication-manager>

	<!-- Enable the annotations for defining the secure role -->
	<global-method-security secured-annotations="enabled" />

Above xml snippet is represented the authentication manager configuration. Here I have used the default authentication manager which is coming with the spring security framework but in the realtime application this authentication manager should be custom and it should be provided the user authentication with existing database. I’ll discuss the custom authentication manager configuration in different blog post.

With the default authentication manager you need to define the users in this xml. You can see here I have defined the two users with the different roles. Make sure that you have configure the “global-method-security” because this is the tag that we are going to say that security roles configuration on resources is in annotation otherwise annotations will be ignored.

Now I’m going to explain the SpringSecurityConfig.java class. This is the class that we are exposing the security configurations to the spring framework.

package spring.security.rest.api;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;


/**
 * Expose the Spring Security Configuration
 * 
 * @author malalanayake
 * 
 */
@Configuration
@ImportResource({ "classpath:webSecurityConfig.xml" })
@ComponentScan("spring.security.rest.api.security")
public class SpringSecurityConfig {

	public SpringSecurityConfig() {
		super();
	}

}

The following class WebConfig.java is the one which is going to expose the rest endpoint. We need ti always point the api implementation package in component scan annotation.

package spring.security.rest.api;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Web Configuration expose the all services
 * 
 * @author malalanayake
 * 
 */
@Configuration
@ComponentScan("spring.security.rest.api.service")
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

	public WebConfig() {
		super();
	}

}

Finally I would like to explain the following service class

package spring.security.rest.api.service;

import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.MediaType;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriComponentsBuilder;

import spring.security.rest.api.entity.CustomerDetails;

import com.google.common.collect.Lists;

/**
 * Customer details exposing as a service. This is secured by spring role base
 * security. This service is only for ROLE_ADMIN
 * 
 * @author malalanayake
 * 
 */
@Controller
@RequestMapping(value = "/customer")
@Secured("ROLE_ADMIN")
public class CustomerDetailService {

	@Autowired
	private ApplicationEventPublisher eventPublisher;

	public CustomerDetailService() {
		super();
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET, consumes = { MediaType.APPLICATION_JSON_VALUE })
	@ResponseBody
	public CustomerDetails findById(@PathVariable("id") final Long id,
			final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
		return new CustomerDetails(randomAlphabetic(6));
	}

	@RequestMapping(method = RequestMethod.GET, consumes = { MediaType.APPLICATION_JSON_VALUE })
	@ResponseBody
	public List<CustomerDetails> findAll() {
		return Lists.newArrayList(new CustomerDetails(randomAlphabetic(6)));
	}

}

You can see I have defined the secure role on top of the class that means this api is going to be available only for who has permission of ROLE_ADMIN.

Lets go to look at how to actually work this web service. First of all you need to build this application and run on the tomcat. Then open the command line and do the following curl command to get the cookie.

curl -i -X POST -d j_username=temporary -d j_password=temporary -c ./cookies.txt http://localhost:8080/spring-security-rest-api/j_spring_security_check

“j_spring_security_check” is default web service that expose from spring framework to get the authentication cookie.

You need to send the username and password as “j_username” and “j_password” parameters. You can see I have used the username and password which has ROLE_ADMIN. finally it will return the session information and it will be saved in cookies.txt

Request-Authentication

Now you can access the service as follows.

curl -i -H “Content-Type:application/json” -X GET -b ./cookies.txt http://localhost:8080/spring-security-rest-api/api/customer

Acess-the-service copy

Now think about the negative scenario. If you going to access the service without proper authentication you will get 401 Unauthorized response.

curl -i -H “Content-Type:application/json” -X GET http://localhost:8080/spring-security-rest-api/api/customer

Unauthorized-2 copy

You can download total project from here

 
25 Comments

Posted by on June 27, 2014 in java, Other, spring

 

Tags: , ,

Building a Charts Dashboard with Google Apps Script


This is grate video about creating dashboards on top of google

 
Leave a comment

Posted by on November 18, 2013 in Other

 

Tags: ,

Website hacking XSS attack


 
Leave a comment

Posted by on March 21, 2013 in Other

 

Tags:

 
%d bloggers like this: