Category: Spring Boot

Spring Boot Custom Banner Example

In this article, i am expecting to demonstrate how to customize the spring boot banner. You may have noticed that a banner is being displayed when the application is up and running. You can customize this banner as your wish.

1.  Google for the word “ascii art generator

2.  Then you will find an ample of resources to generate ASCII characters. You can use one of the found resources to  generate the ASCII characters for your desired text. (I have used the http://patorjk.com for generating ASCII value.)

 

Screen Shot 2017-11-01 at 1.10.26 AM

 

3.  Finally copy the ASCII characters to file called banner.txt and put in the resources directory.

Screen Shot 2017-11-01 at 1.18.41 AM

 

4.  Then build and run the application. you will see the newly customized banner when your application is being loaded and run.

Screen Shot 2017-11-01 at 1.17.09 AM

 

The complete source code of the example can be found at GitHub

Converting Spring Boot JAR file into Tomcat deployable WAR file

By default, the spring boot applications are bundled into JAR regardless of its nature (web or stand alone app). Sometimes we need to create WAR file and deploy them in the tomcat server. In this article we are going to explore, how the spring boot application change in a way to create tomcat deployable WAR file.

In this application,  maven will be used as the build and dependency management tool.

The first step in producing a deployable war file is to provide a SpringBootServletInitializer subclass and override its configure method. This makes use of Spring Framework’s Servlet 3.0 support and allows you to configure your application when it’s launched by the servlet container. Typically, you update your application’s main class to extend SpringBootServletInitializer:

@SpringBootApplication
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}

view raw
Application.java
hosted with ❤ by GitHub

The next step is to update your build configuration so that your project produces a war file rather than a jar file. If you’re using Maven and using spring-boot-starter-parent (which configures Maven’s war plugin for you) all you need to do is to modify pom.xml to change the packaging to war:

<packaging>war</packaging>

The final step in the process is to ensure that the embedded servlet container doesn’t interfere with the servlet container to which the war file will be deployed. To do so, you need to mark the embedded servlet container dependency as provided.

<dependencies>
<!––>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!––>
</dependencies>

view raw
pom.xml
hosted with ❤ by GitHub

Now you can use the below maven command to build the application.

mvn package

References: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-create-a-deployable-war-file

Securing Spring REST Api with Spring Security and JWT (Json Web Token)

In this article, i am going to demonstrate how to user JWT (Json Web Token) Authentication with Spring boot and Spring Security.  In here, i am not going to discuss the basic theory and details about the JWT and you can search google and find a lot of resources related to that.

GitHub URL :-  https://github.com/chathurangat/spring-rest-jwt-auth-example 

I will update a screenshot of my project structure to get an idea of project structure and class/files locations. Don’t worry! This is just to get an idea. We will be doing everything one by one as we are proceeding.

Screen Shot 2017-07-17 at 3.07.00 PM

Before starting with the development, i will briefly give you an idea about the classes that we are going to develop in this article.
First step is to create spring boot web project. This can be easily created with Spring Initializer (https://start.spring.io/). Remember to add web and spring security dependencies for your app.  In addition to that, it is important to add JWT dependency.

Required dependencies in pom.xml

<?xml version="1.0" encoding="UTF-8"?>
	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.6.0</version>
        </dependency>

	</dependencies>

Then create a JwtService class as below. The JwtService class will be used for following two purposes.

  • Generate JWT token based on username upon successful user login.
  • Validate /Authenticate JWT token (user send along with every request)  and extract user information from the token.

JwtService.java 


import com.chathuranga.rest.jwt.auth.SecretKeyProvider;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.time.LocalDateTime;
import java.util.Date;

import static java.time.ZoneOffset.UTC;

@Component
public class JwtService {

    private static final String ISSUER = "com.chathuranga.examples";

    @Autowired
    private SecretKeyProvider secretKeyProvider;

    public String generateToken(String username) throws IOException, URISyntaxException {
        byte[] secretKey = secretKeyProvider.getKey();
        Date expiration = Date.from(LocalDateTime.now(UTC).plusHours(2).toInstant(UTC));
        return Jwts.builder()
                .setSubject(username)
                .setExpiration(expiration)
                .setIssuer(ISSUER)
                .signWith(SignatureAlgorithm.HS512, secretKey)
                .compact();
    }

    public String verifyToken(String token) throws IOException, URISyntaxException {
        byte[] secretKey = secretKeyProvider.getKey();
        Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
        //returning authenticated/verified username
        return claims.getBody().getSubject();
    }
}

Now we need to create a LoginController for authenticating users with their credentials (username and password) and issue JWT token (using JwtService) upon successful authentication

LoginController.java


import com.chathuranga.rest.jwt.auth.exception.FailedToLoginException;
import com.chathuranga.rest.jwt.auth.model.AuthenticationResponse;
import com.chathuranga.rest.jwt.auth.model.UserCredentials;
import com.chathuranga.rest.jwt.auth.service.UserAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
public class LoginController {

    @Autowired
    private UserAuthenticationService authenticationService;

    @ResponseStatus(HttpStatus.OK)
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public AuthenticationResponse userLogin(@RequestBody UserCredentials userCredentials) throws FailedToLoginException {

        if (userCredentials == null || (userCredentials.getUsername() == null || userCredentials.getPassword() == null)) {
            throw new FailedToLoginException("Missing login credentials ");
        }

        String token = authenticationService.authenticateUser(userCredentials.getUsername(), userCredentials.getPassword());

        if (token != null) {
            AuthenticationResponse authenticationResponse = new AuthenticationResponse();
            authenticationResponse.setUsername(userCredentials.getUsername());
            authenticationResponse.setToken(token);
            return authenticationResponse;
        }
        throw new FailedToLoginException(String.format(" unable to authenticate user [%s] ", userCredentials.getUsername()));
    }
}

Here is the Implementation of the UserAuthenticationService class. For the demonstration purpose i have hard coded two user credentials. But in production environment, you need to implement JPA based user repository or some other mechanism like LDAP or OpenId.

UserAuthenticationService.java


import com.chathuranga.rest.jwt.auth.exception.FailedToLoginException;
import com.chathuranga.rest.jwt.auth.exception.JwtAuthenticationException;
import com.chathuranga.rest.jwt.auth.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

@Component
public class UserAuthenticationService {

    @Autowired
    private JwtService jwtService;

    @Autowired
    private UserService userService;

    public String authenticateUser(String username, String password) throws FailedToLoginException {
        boolean isAuthenticated = false;
        if (username.equals("chathuranga") && password.equals("test123")) {
            isAuthenticated = true;
        } else if (username.equals("bob") && password.equals("test123")) {
            isAuthenticated = true;
        }

        if (isAuthenticated) {
            try {
                return jwtService.generateToken(username);
            } catch (URISyntaxException | IOException e) {
                throw new FailedToLoginException(e.getMessage());
            }
        }
        throw new FailedToLoginException(String.format("unable to authenticate user [%s]", username));
    }

    public User authenticateToken(String jwtToken) throws JwtAuthenticationException {

        try {
            String username = jwtService.verifyToken(jwtToken);
            List<String> userRoles = userService.getUserRoles(username);

            User user = new User();
            user.setUsername(username);
            user.setUserRoles(userRoles);
            return user;
        } catch (IOException | URISyntaxException e) {
            throw new JwtAuthenticationException(e.getMessage(), e);
        }
    }
}

One more thing! I forgot to show you the implementation of AuthenticationResponse class.
This is just a POJO class implemented to return the successful authentication response back to the client. Here is the implementation. You will notice that we are returning username and JWT token back to the client.

AuthenticationResponse.java


package com.chathuranga.rest.jwt.auth.model;

public class AuthenticationResponse {

    private String username;
    private String token;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

Once this LoginController is fully developed, we should be able to authenticate users with their credentials. We have hardcoded few user credentials. I am going to test the user authentication with those credentials using Postman tool.

Username: chathuranga
Password: test123

Username: bob
Password: test123

Here is my Postman request.

Screen Shot 2017-07-17 at 4.33.39 PM

Here is the response retrieved. You can see that i am getting the username and JWT token as the response.

Now we have the JWT token. So we can use this token to show our authenticity.

Accessing Secured Api

Please refer the below secured controller. It has two methods to support for two endpoint URLs.

1. /api/admin/hello – this can be accessed only by users with ROLE_ADMIN
2. /api/user/hello – this can be accessed only by users with ROLE_USER


package com.chathuranga.rest.jwt.controller;

import org.springframework.http.HttpMethod;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api")
public class WelcomeController {

    @Secured("ROLE_ADMIN")
    @RequestMapping(path = "/admin/hello", method = RequestMethod.GET)
    public String helloAdminController() {
        String loggedUserName = SecurityContextHolder.getContext().getAuthentication().getName();

        return "Hello Admin " + loggedUserName;
    }

    @Secured("ROLE_USER")
    @RequestMapping(path = "/user/hello", method = RequestMethod.GET)
    public String helloUserController() {

        String loggedUserName = SecurityContextHolder.getContext().getAuthentication().getName();

        return "Hello User " + loggedUserName;
    }
}

Please refer the following Postman screenshot.

Screen Shot 2017-07-17 at 3.03.31 PM

Spring Security Related Configurations and Implementation Classes

SecurityConfig.java


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthFilter authFilter;

    @Autowired
    private JwtAuthenticationProvider authenticationProvider;

    @Autowired
    private JwtAuthenticationEntryPoint authenticationEntryPoint;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().ignoringAntMatchers("/login");

        http.authorizeRequests()
                .antMatchers("/login")
                .permitAll()
                .antMatchers("/api/**")
                .authenticated()
                .and()
                .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint);
    }
}

  • Here we have used a custom authentication provider called JwtAuthenticationProvider. It will be used to authenticate users , based on JWT token.  
  • We have disabled the CSRF token validation for URL  /login.  
  • Any request coming to /login will be permitted and any request coming to URL /api/** should be authenticated.
  • We have created a custom Filter (JwtAuthFilter) and it will be applied before executing UsernamePasswordAuthenticationFilter

Any authentication related exception will be handled using the custom authentication entry point provided.(That is JwtAuthenticationEntryPoint)

JwtAuthFilter.java

This filter will be used to capture the JWT token sent by the users through Authorization header. This will find the JWT token in the request header and set it in the Authentication object before executing the UsernamePasswordAuthenticationFilter provided by the Spring security.

(The filter creates an instance of  JwtAuthToken class with token retrieved and set it as  the current Authentication object for the request)

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class JwtAuthFilter implements Filter
{

    @Override
    public void doFilter(ServletRequest request, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        String authorization = servletRequest.getHeader("Authorization");

        if (authorization != null)
        {
            JwtAuthToken token = new JwtAuthToken(authorization.replaceAll("Bearer ", ""));
            SecurityContextHolder.getContext().setAuthentication(token);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy()
    {

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }
}

 

JwtAuthenticationProvider.java

import com.chathuranga.rest.jwt.auth.model.User;
import com.chathuranga.rest.jwt.auth.service.UserAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

@Component
public class JwtAuthenticationProvider implements AuthenticationProvider
{

    @Autowired
    private UserAuthenticationService authenticationService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException
    {
      User user =  authenticationService.authenticateToken((String) authentication.getCredentials());
      return new JwtAuthenticatedUserToken(user.getUsername(),user.getUserRoles());
    }

    /*
     Returns true if this AuthenticationProvider supports the indicated Authentication object.
     */
    @Override
    public boolean supports(Class<?> aClass)
    {
        return JwtAuthToken.class.equals(aClass);
    }
}

The JwtAuthenticationProvider receives the Authentication instance set on the SecurityContext, which in our case is the JwtAuthToken we set using the JwtAuthFilter. This token is then verified using the JwtService. If the token is valid, we return a JwtAuthenticatedUserToken (username and ACL – Access Control List) or throw an AuthenticationException if it is invalid. Any authentication related exception (an instance of AuthenticationException) will be handled by JwtAuthenticationEntrypoint.

JwtAuthenticationEntryPoint.java

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint
{
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e)
            throws IOException, ServletException {
        httpServletResponse.setStatus(SC_FORBIDDEN);
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);

        String message;
        if(e.getCause() != null) {
            message = e.getCause().getMessage();
        } else {
            message = e.getMessage();
        }
        byte[] body = new ObjectMapper()
                .writeValueAsBytes(Collections.singletonMap("error", message));
        httpServletResponse.getOutputStream().write(body);
    }
}

Spring MVC : What is @RequestBody and @ResponseBody ?

 

@RequestBody and @ResponseBody annotations are used to convert the body of the HTTP request and response with java class objects. Both these annotations will use registered HTTP message converters in the process of converting/mapping HTTP request/response body with java objects.

The source code for this article can be found in the GitHub.

Click here to download the source code.

What is the HTTP Message Converter and Why it is used?

The client (web browser or REST client) cannot send the java objects (as it is) in the body of the HTTP request. On the other hand, the server application cannot compose the body of the HTTP response with java objects (as it is). Simply the HTTP Request and Response body cannot contains the in the form of java objects.

HTTP request and response body should contain either JSON , XML or some other type of formatted data (RSS etc).  Therefore the HTTP message converters are used to convert the HTTP request body (either in JSON or XML) to the Java objects and Java objects back to XML or JSON for embedding into the HTTP response body.

 

How the Message Converter Works?

you might be having a little confusion of how message converters are exactly worked. How the spring frameworks picks the right message converter that can transform the HTTP request body into the targeted java class object. On the other hand, how the server application responds back with exactly the similar type (either XML or JSON) that is expected by the client.  This is achieved by checking the headers of the HTTP request. Lets look at what are those headers in detailed.

 

Content-Type 

This header informs the server application about the content type of the body of the HTTP Request. Based on the content type, the server application picks the correct message converter out of the available message converters  for converting the HTTP Request body into the java class object.

e.g:-

  • If the Content-Type is application/json , then it will select a JSON to Java Object converter.
  • If the Content-Type is application/xml , then it will select a XML to Java Object converter.

 

Accept

This header informs the server application about the Acceptable media type of the body of the HTTP Response (Simply what the client will accept from the server). Based on the value of the Accept header, the server application picks the correct message converter out of the available message converters  for converting returned java class object(s) to the requested media type.

e.g:-

  • If the Accept is application/json , then it will select a Java Object to JSON converter.
  • If the Accept is application/xml ,  then it will select a Java Object to XML converter.

 

@RequestBody

This is used to convert the body of the HTTP request to the java class object with the aid of selected HTTP message converter. This annotation will be used in the method parameter and the body of the http request will be mapped to that method parameter. As described above, the message converter is selected based on the value of Content-Type  Header of the HTTP request.

 

@ResponseBody

This annotation is used to add the return value to the body of the HTTP response with the aid of selected HTTP message converter. As described above, the message converter is selected based on the value of Accept Header of the HTTP request. @RestController is the preferred way to achieve the same functionality earlier provided by @ResponseBody. Under the hood, @RestController is @Controller + @ResponseBody, and it avoids the need of prefixing every method with @ResponseBody.

 

Ok. enough theories. Lets do some cool stuffs with coding.  You can download the following samples from GitHub.

 

The following dependency has been added to configure/register the  HTTP message converter for XML type.

 <dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
 </dependency>

 

The source code of UserController has posted below and you can see that the single method available there. It can accept request body with both JSON and XML content types. In addition, it can produces both JSON and XML content types in response body.

 

import com.springbootdev.examples.domain.entity.User;
import com.springbootdev.examples.domain.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.http.MediaType.*;
@RestController
@RequestMapping("/api")
public class UserController
{
@Autowired
private UserRepository userRepository;
@PostMapping(
value = "/users",
consumes = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE},
produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE}
)
public User create(@RequestBody User user)
{
return userRepository.save(user);
}
}

view raw
UserController.java
hosted with ❤ by GitHub

 

@RequestBody will help to convert the body of the HTTP Request to the User object.  The method can handle a request body that is in the form of either XML or JSON.  The transformed user object will be saved to database using the userRepository. The persisted user object will be retuned by the method.

Since the class is annotated with @RestController, every method in the class is implicitly annotated with @ResponseBody.  Therefore the returned value/object will substitute the body of the HTTP Response. The body of the HTTP Response can be either XML or JSON.

Before building and running the application, make sure that you have changed the datasource configurations of  the application.properties to your development environment.

 

## Spring DATA SOURCE Configurations
spring.datasource.url = jdbc:mysql://localhost:3306/spring_examples_db?useSSL=false
spring.datasource.username = root
spring.datasource.password = test123
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

 

Ok lets run the application and make few api calls with Postman.

 

Round 1

POST   /api/users

Content-Type : application/json
Accept : application/json

Screen Shot 2018-01-01 at 11.31.51 PM.png

 

Request Body and Response Body

Screen Shot 2018-01-01 at 11.31.14 PM.png

 

Round 2

POST   /api/users

Content-Type : application/json
Accept : application/xml

 

Request Body and Response Body

Screen Shot 2018-01-01 at 11.35.57 PM.png

 

Round 3

POST   /api/users

Content-Type : application/xml
Accept : application/xml

 

Request Body and Response Body

Screen Shot 2018-01-01 at 11.37.49 PM.png

 

Round 4

POST   /api/users

Content-Type : application/xml
Accept : application/json

 

Request Body and Response Body

Screen Shot 2018-01-01 at 11.39.46 PM.png

 

 

ResponseEntity

I just wanted to explain you  about the ResponseEntity even if it is not mentioned in the code example.

ResponseEntity is a real deal. It represents the entire HTTP response. Good thing about it is that you can control anything that goes into it. You can specify status code, headers, and body. It comes with several constructors to carry the information you want to sent in HTTP Response.

 

Spring Boot : How does @EnableAutoConfiguration annotation works?

Spring Boot framework allows to create spring based applications with minimizing the effort of doing manual spring configurations. Spring Boot automatically do the configuration on behalf of the developer. You might be wonder how does the spring boot framework do the configuration automatically.

                This is done with the @EnableAutoConfiguration annotation available in the Spring framework. @EnableAutoConfiguration will automatically do the spring configurations. it will create, register and load the Spring configuration beans required by the applications from the classes available in the class path.

e.g:- For example if  JpaRepository class is present on the class path, then the RabbitAutoConfiguration will be enabled.

Spring Boot is designed so that you can gradually replaced the auto-configuration as needed. To exclude an auto configuration, use the exclude attribute of the @EnableAutoConfiguration annotation as below:

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})