Search Tutorials


Implement Spring Boot RestTemplate + JWT Authentication Example

Spring Boot RestTemplate + JWT Authentication Example

In a previous tutorial we had implemented Spring Boot + MYSQL + JWT Authentication Example
Previously we had consumed the exposed service using external client like Postman. But we may also need to call this JWT authenticated service from some other microservice. In this tutorial we will be consuming the JWT authenticated exposed service programmatically using RestTemplate. Using the Spring Boot RestTemplate as the client we will be performing the following operations-
Spring Boot RestTemplate JWT Example

Video

This tutorial is explained in the below Youtube Video.

Spring Boot JSON Web Token- Table of Contents

Understanding the need for JSON Web Token(JWT) Understanding JWT Structure Implement Spring Boot Security Implement Spring Boot + JSON Web Token Security Implement Spring Boot Security + JSON Web Token + MySQL Spring Boot RestTemplate + JWT Authentication Example Spring Boot Security - Refresh Expired JSON Web Token Angular 7 + Spring Boot JWT Authentication Hello World Example Online JWT Generator Online JWT Decoder

Lets Begin

The maven project will be as follows-
Spring Boot RestTemplate JWT Maven
Define the pom.xml as follows-
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.javainuse</groupId>
	<artifactId>spring-boot-jwt-consume</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>SpringBootHelloWorld</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.4.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

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

</project>
Define the properties as follows-
server.port: 8081




Create the domain class named User as follows. This class will be used for User Authentication.
package com.javainuse.model;

public class User {

	private String username;
	private String password;

	public String getUsername() {
		return username;
	}

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

	public String getPassword() {
		return password;
	}

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

}

Create the domain class named RegistrationUser as follows. This class will be used for User Registration. This class extends the User class and has additional field role.
package com.javainuse.model;

public class RegistrationUser extends User {

	private String role;

	public String getRole() {
		return role;
	}

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

}
Create the ResponseToken class. This will hold the JWT response returned on successful authentication.
package com.javainuse.model;

public class ResponseToken {

	private String token;

	public String getToken() {
		return token;
	}

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

Define the Bootstrap class with the @SpringBootApplication annotation. Also in this class we will be creating the bean of type RestTemplate.
package com.javainuse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class SpringBootJwtConsumeApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootJwtConsumeApplication.class, args);
	}

	@Bean
	public RestTemplate getRestTemplate() {
		return new RestTemplate();
	}
}
Finally create the TestController class. In this class we will be autowiring the RestTemplate bean we had created previously. Using the RestTemplate we will
  • Register new User
  • Authenticate the registered User to get JWT
  • Using JWT make a call to the hello world service
package com.javainuse.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.javainuse.model.RegistrationUser;
import com.javainuse.model.ResponseToken;
import com.javainuse.model.User;

@RestController
public class TestController {

	@Autowired
	RestTemplate restTemplate;

	private static final String REGISTRATION_URL = "http://localhost:8080/register";
	private static final String AUTHENTICATION_URL = "http://localhost:8080/authenticate";
	private static final String HELLO_URL = "http://localhost:8080/helloadmin";

	@RequestMapping(value = "/getResponse", method = RequestMethod.GET)
	public String getResponse() throws JsonProcessingException {

		String response = null;
		// create user registration object
		RegistrationUser registrationUser = getRegistrationUser();
		// convert the user registration object to JSON
		String registrationBody = getBody(registrationUser);
		// create headers specifying that it is JSON request
		HttpHeaders registrationHeaders = getHeaders();
		HttpEntity<String> registrationEntity = new HttpEntity<String>(registrationBody, registrationHeaders);

		try {
			// Register User
			ResponseEntity<String> registrationResponse = restTemplate.exchange(REGISTRATION_URL, HttpMethod.POST,
					registrationEntity, String.class);
			   // if the registration is successful		
			if (registrationResponse.getStatusCode().equals(HttpStatus.OK)) {

				// create user authentication object
				User authenticationUser = getAuthenticationUser();
				// convert the user authentication object to JSON
				String authenticationBody = getBody(authenticationUser);
				// create headers specifying that it is JSON request
				HttpHeaders authenticationHeaders = getHeaders();
				HttpEntity<String> authenticationEntity = new HttpEntity<String>(authenticationBody,
						authenticationHeaders);

				// Authenticate User and get JWT
				ResponseEntity<ResponseToken> authenticationResponse = restTemplate.exchange(AUTHENTICATION_URL,
						HttpMethod.POST, authenticationEntity, ResponseToken.class);
					
				// if the authentication is successful		
				if (authenticationResponse.getStatusCode().equals(HttpStatus.OK)) {
					String token = "Bearer " + authenticationResponse.getBody().getToken();
					HttpHeaders headers = getHeaders();
					headers.set("Authorization", token);
					HttpEntity<String> jwtEntity = new HttpEntity<String>(headers);
					// Use Token to get Response
					ResponseEntity<String> helloResponse = restTemplate.exchange(HELLO_URL, HttpMethod.GET, jwtEntity,
							String.class);
					if (helloResponse.getStatusCode().equals(HttpStatus.OK)) {
						response = helloResponse.getBody();
					}
				}
			}
		} catch (Exception ex) {
			System.out.println(ex);
		}
		return response;
	}

	private RegistrationUser getRegistrationUser() {
		RegistrationUser user = new RegistrationUser();
		user.setUsername("javainuse");
		user.setPassword("javainuse");
		user.setRole("ROLE_ADMIN");
		return user;
	}

	private User getAuthenticationUser() {
		User user = new User();
		user.setUsername("javainuse");
		user.setPassword("javainuse");
		return user;
	}

	private HttpHeaders getHeaders() {
		HttpHeaders headers = new HttpHeaders();
		headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
		headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
		return headers;
	}

	private String getBody(final User user) throws JsonProcessingException {
		return new ObjectMapper().writeValueAsString(user);
	}

}
Start the Spring Boot + JWT + MySQL Project we had developed previously.
Start the Spring Boot Project we have developed in this tutorial. If we now go to http://localhost:8081/getResponse
Spring Boot RestTemplate JWT Authentication

Download Source Code

Download it -
Spring Boot RestTemplate + JWT Authentication Example