RSS

Stateless Spring Security on REST API


First I would like you to go through my previous blog post that I have written for Spring Security on REST Api. In the above spring security scenario based on state full mechanism. It is using the default user details service which is defined through the security.xml but we know that once we are going to develop real world application those use the custom user stores to store the user details so we need to plug those databases to our authentication process. Another thing that we know in the REST apis should be stateless so what I’m going to show you how to secure the REST Api with stateless basic authentication by using the custom user details service.

First of all you need to understand the flow of this security mechanism. See the following diagram.

Spring-Security

Lets look at the configuration and cording. I assume that you have clear idea about spring security configuration so I’m not going to explain each and every thing on this project. If you have doubt about the spring configurations please follow my previous post carefully.

webSecurityConfig.xml

<?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" create-session="stateless"
		entry-point-ref="restServicesEntryPoint" authentication-manager-ref="authenticationManagerForRest">
		<intercept-url pattern="/api/**" />
		<sec:form-login authentication-success-handler-ref="mySuccessHandler" />
		<sec:access-denied-handler ref="myAuthenticationAccessDeniedHandler" />
		<http-basic />
	</http>

	<!-- Entry point for REST service. -->
	<beans:bean id="restServicesEntryPoint"
		class="spring.security.custom.rest.api.security.RestAuthenticationEntryPoint" />

	<!-- Custom User details service which is provide the user data -->
	<beans:bean id="customUserDetailsService"
		class="spring.security.custom.rest.api.security.CustomUserDetailsService" />

	<!-- Connect the custom authentication success handler -->
	<beans:bean id="mySuccessHandler"
		class="spring.security.custom.rest.api.security.RestAuthenticationSuccessHandler" />

	<!-- Using Authentication Access Denied handler -->
	<beans:bean id="myAuthenticationAccessDeniedHandler"
		class="spring.security.custom.rest.api.security.RestAuthenticationAccessDeniedHandler" />

	<!-- Authentication manager -->
	<authentication-manager alias="authenticationManagerForRest">
		<authentication-provider user-service-ref="customUserDetailsService" />
	</authentication-manager>

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

</beans:beans>

Now you can focus on the http configuration in above xml. Within the http name tag you can see I have defined the http-basic that means this url should be secured by basic authentication. You have to send the username and password by Base64 encoding as follows.

admin:adminpass encoded by Base64 (YWRtaW46YWRtaW5wYXNz)

Second main point of this project is custom user detail service. As I mentioned earlier in the real world application you have to use the existing authentication source to do the authentication.

package spring.security.custom.rest.api.security;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * CustomUserDetailsService provides the connection point to external data
 * source
 * 
 * @author malalanayake
 * 
 */
public class CustomUserDetailsService implements UserDetailsService {
	private String USER_ADMIN = "admin";
	private String PASS_ADMIN = "adminpass";

	private String USER = "user";
	private String PASS = "userpass";

	@Override
	public UserDetails loadUserByUsername(String authentication) throws UsernameNotFoundException {
		CustomUserData customUserData = new CustomUserData();
		// You can talk to any of your user details service and get the
		// authentication data and return as CustomUserData object then spring
		// framework will take care of the authentication
		if (USER_ADMIN.equals(authentication)) {
			customUserData.setAuthentication(true);
			customUserData.setPassword(PASS_ADMIN);
			Collection<CustomRole> roles = new ArrayList<CustomRole>();
			CustomRole customRole = new CustomRole();
			customRole.setAuthority("ROLE_ADMIN");
			roles.add(customRole);
			customUserData.setAuthorities(roles);
			return customUserData;
		} else if (USER.equals(authentication)) {
			customUserData.setAuthentication(true);
			customUserData.setPassword(PASS);
			Collection<CustomRole> roles = new ArrayList<CustomRole>();
			CustomRole customRole = new CustomRole();
			customRole.setAuthority("ROLE_USER");
			roles.add(customRole);
			customUserData.setAuthorities(roles);
			return customUserData;
		} else {
			return null;
		}
	}

	/**
	 * Custom Role class for manage the authorities
	 * 
	 * @author malalanayake
	 * 
	 */
	private class CustomRole implements GrantedAuthority {
		String role = null;

		@Override
		public String getAuthority() {
			return role;
		}

		public void setAuthority(String roleName) {
			this.role = roleName;
		}

	}

}

In the above code you can see I have implemented the UserDetailsService interface and override the method loadUserByUsername. Within this method you need to connect to the external user store and get the credentials and the roles associated with the user name. I have hardcoded the values for your understanding.

Another special thing is you need to pass the object which is implemented by the UserDetails so you can see I have created the following class for that.

package spring.security.custom.rest.api.security;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * This class is provide the user details which is needed for authentication
 * 
 * @author malalanayake
 * 
 */
public class CustomUserData implements UserDetails {
	Collection<? extends GrantedAuthority> list = null;
	String userName = null;
	String password = null;
	boolean status = false;

	public CustomUserData() {
		list = new ArrayList<GrantedAuthority>();
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return this.list;
	}

	public void setAuthorities(Collection<? extends GrantedAuthority> roles) {
		this.list = roles;
	}

	public void setAuthentication(boolean status) {
		this.status = status;
	}

	@Override
	public String getPassword() {
		return this.password;
	}

	public void setPassword(String pass) {
		this.password = pass;
	}

	@Override
	public String getUsername() {
		return this.userName;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

}

Finally we need to take care of the unauthenticated responses so there are two possibilities that we can throw the 401 Unauthorized response.

1. User come to access the service without proper authentication. Then the spring framework redirect the user to get the authentication but this is a REST api so we don't need to redirect the user to get the authentication thats why we simply pass the 401 response in RestAuthenticationEntryPoint class.

package spring.security.custom.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 their authentication.
 * 
 * @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");

	}

}

2. Second possible scenario is user has proper authentication but he doesn't have proper authorization that means he doesn't have the proper ROLE. This scenario spring framework push the request to the RestAuthenticationAccessDeniedHandler then we need to simply pass the 401 Unauthorized response. If we didn't set this handler the spring framework push the 403 Forbidden response.

package spring.security.custom.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.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

public class RestAuthenticationAccessDeniedHandler implements AccessDeniedHandler {

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response,
			AccessDeniedException arg2) throws IOException, ServletException {
		response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");

	}
}

I hope you will enjoy the spring security with REST Api. You can download the total source of this project from here.

 
Leave a comment

Posted by on June 30, 2014 in java, spring

 

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

 
4 Comments

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

 

Tags: , ,

Simple LinkedList Implementation with Java Generics


Java generics are introduced with in 2004 J2SE 1.5. This concept is really important and it will help a lot in programing. I’m not going to explain the whole generics concept here but I will use the generics to implement the LinkedList. With the generics you don’t want to do the type casting anymore that will really avoid the runtime exceptions. See the following code snippet and enjoy your programming.

 
Leave a comment

Posted by on June 15, 2014 in data-structures, java

 

Tags: , ,

Simple ArrayList Implementation


The post will be useful to keep your mind refresh about the array list implementation. If you are a beginner you have to understand the concepts of simple array list and how it will work.

 
Leave a comment

Posted by on June 15, 2014 in data-structures, java

 

Tags: , ,

Simple Linked List Implementation in Java


Data structures are very important in software development and Linked List is one of commonly using data structures in the development. Most of the time people who are new to software engineering they need to implement well known data structure in their point of view to understand the concepts. So I think this code snippet will help for beginners to learn how to implement the LinkedList in Java.

This is a really simple one but you can do some modification on this and make it as advanced structure.

 
1 Comment

Posted by on June 9, 2014 in data-structures

 

Tags: , ,

Access Levels in Java


Most people confused with the access modifiers in java so lets talk little bit about it. The confusing part is “private” and “not defined modifier” as an example if declared the two variables with in the class as follows then where I can access those

private int can_see_for_class;
int can_see_with_in_package;  

Java by default it has been assigned the package private that means you can access your variable with in the same package.

Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

Private : Like you'd think, only the class in which it is declared can see it.
Package Private : Can only be seen and used by the package in which it was declared.
Protected : Package Private + can be seen by subclasses or package member.
Public : Everyone can see it.

 
Leave a comment

Posted by on June 8, 2014 in java

 

Tags: , ,

REST API Documentation with Swagger


This is going to focus REST API documentation with Swagger. We know that REST APIs are very popular with modern world technology and most of the technology solutions came up with REST Implementations. Developers who are involved with the REST APIs development and they have kind of problem like how to document the REST APIs and how to simply expose those REST APIs to the end users. Swagger is good solution for above explained problem. So lets talk about swagger integration to the JAX-RS API. I think that you are familiar with the JAVA JAX-RS implementations. If not you have to get some knowledge about JAX-RS implementation.

1. You have to add swagger maven artifact to your project.

2. Secondly you have to mentioned the base path on your web.xml. This URL will be used as backend service call from swagger-ui

3. Finally you have to annotate your REST-APIs by swagger annotations. You can get total idea from following code snippets.

4. Then you have to get the swagger-ui and host it on your local tomcat.

5. Now you can simply view and invoke the REST APIs which is developed by you by using the Swagger UI.

test

test2

 
2 Comments

Posted by on March 25, 2014 in java

 

Tags: , , ,

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: