Category Archives: Java

Spring WebClient vs RestTemplate – Comparison and Features

Introduction

Spring 5 introduced a new reactive web client called WebClient. In this post, I will show when and how we can use Spring WebClient vs RestTemplate. I will also describe what features WebClient offers.

What is RestTemplate?

RestTemplate is a central Spring class that allows HTTP access from the client-side. RestTemplate offers POST, GET, PUT, DELETE, HEAD, and OPTIONS HTTP methods. The simple use case of RestTemplate is to consume Restful web services.

You can create a bean that provides the instance of RestTemplate. You can then @autowire this bean in any class where you plan to call REST services. RestTemplate is the class that implements the interface RestOperations.

The following code shows the declaration of the bean:

    @Bean
    public RestOperations restOperations()
    {
        return new RestTemplate();
    }

The following code shows a REST client `YelpClient` calling Yelp’s REST API to get rental property reviews.

   @Autowired
   private final RestOperations restOperations;

   public List getRentalPropertyReviews(String address)
   {
        String url = buildRestUrl(businessId);
        HttpHeaders httpHeaders = new HttpHeaders();
        String apiKey = getApiKey(YELP);
        httpHeaders.add("Authorization","Bearer " + apiKey);
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity entity = new HttpEntity("parameters", httpHeaders);
        ResponseEntity response;

        try
        {
            response = restOperations.exchange(url, HttpMethod.GET,entity, String.class);
        }
        catch(RestClientException e)
        {
            throw new RuntimeException("Unable to retrieve reviews", e);
        }

    }

In the above code, we are building HTTP Headers by adding Yelp’s REST API key as part of the authorization. We call the GET method to get review data.

Basically, one has to do

  • Autowire the RestTemplate object
  • Build HTTP Headers with authorization and Content Type
  • Use HttpEntity to wrap the request object
  • Provide URL, Http Method, and the Return type for exchange method.

What is WebClient?

Spring 5 introduced a reactive web client called WebClient. It’s an interface to perform web requests. It is part of the Spring web reactive module. WebClient will be replacing RestTemplate eventually.

Most importantly, WebClient is reactive, nonblocking, asynchronous, and works over HTTP protocol Http/1.1.

To use WebClient, one has to do

  • Create an instance of WebClient
  • Make a request to the REST endpoint
  • handle the response

 

   WebClient webClient = WebClient
       .builder()
       .baseUrl("https://localhost:8443")
       .defaultCookie("cookieKey", "cookieValue")
       .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) 
       .defaultUriVariables(Collections.singletonMap("url", "https://localhost:8443"))
       .build();

The above code shows one way to instantiate WebClient. You can also create an instance by simply using WebClient webClient = WebClient.create();

WebClient provides two methods exchange and retrieve . exchange method usually fetches the response along with status and headers. retrieve method gets the response body directly. It’s easier to use.

Also depending on if you are trying to fetch a single object in response or a list of objects, you can use mono or flux.

this.webClient =
                webClientBuilder.baseUrl("http://localhost:8080/v1/betterjavacode/").build();

this.webClient.get()
                .uri("users")
                .accept(MediaType.APPLICATION_JSON)
                .retrieve().bodyToFlux(UserDto.class).collectList();

The above code basically uses webClient to fetch a list of users from the REST API.

Spring WebClient vs RestTemplate

We already know the one key difference between these two features. WebClient is a non-blocking client and RestTemplate is a blocking client.

RestTemplate uses Java Servlet API under the hood. Servlet API is a synchronous caller. Because it is synchronous, the thread will block until webclient responds to the request.

Consequently, Requests waiting for results will increase. This will result in an increase in memory.

On the other hand, WebClient is an asynchronous non-blocking client. It uses Spring’s reactive framework under the hood. WebClient is a part of the Spring-WebFlux module.

Spring WebFlux uses reactor library. It provides Mono and Flux API to work data sequences. Reactor is a reactive streams library. And, all of its operators support non-blocking back pressure.

Example of how to use WebClient in a Spring Boot Application

We can combine the capabilities of Spring Web MVC and Spring WebFlux. In this section, I will create a sample application. This application will call a REST API using WebFlux and we will build a response to show a web page with a list of users.

RestController for this example is an API to get a list of users:

package com.betterjavacode.webclientdemo.controllers;

import com.betterjavacode.webclientdemo.dto.UserDto;
import com.betterjavacode.webclientdemo.managers.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("v1/betterjavacode")
public class UserController
{
    @Autowired
    public UserManager userManager;

    @GetMapping(value = "/users")
    public List getUsers()
    {
        return userManager.getAllUsers();
    }
}

Controller class that uses a WebClient to call REST API looks like below:

package com.betterjavacode.webclientdemo.controllers;

import com.betterjavacode.webclientdemo.clients.UserClient;
import com.betterjavacode.webclientdemo.dto.UserDto;
import com.betterjavacode.webclientdemo.managers.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Controller
public class MainController
{
    @Autowired
    UserClient userClient;

    @GetMapping(value = "/")
    public String home()
    {
        return "home";
    }

    @GetMapping(value = "/users")
    public String getUsers(Model model)
    {
        List users = userClient.getUsers().block();

        model.addAttribute("userslist", users);
        return "users";
    }
}

Now, the important piece of code of UserClient is where we will be using WebClient to call REST API.

package com.betterjavacode.webclientdemo.clients;

import com.betterjavacode.webclientdemo.dto.UserDto;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

@Service
public class UserClient
{

    private WebClient webClient;

    public UserClient(WebClient.Builder webClientBuilder)
    {
        this.webClient =
                webClientBuilder.baseUrl("http://localhost:8080/v1/betterjavacode/").build();
    }

    public Mono<List> getUsers()
    {
        return this.webClient.get()
                .uri("users")
                .accept(MediaType.APPLICATION_JSON)
                .retrieve().bodyToFlux(UserDto.class).collectList();
    }
}

Above code shows first building the WebClient and then using it to retrieve response from REST API. retrieve method offers two options of mono or flux. Since we have more than one user to get, we are using flux.

This shows we can use reactive, non-blocking WebClient which is part of WebFlux in Spring Web MVC framework.

What Else Is There in Spring WebClient?

Spring WebClient is part of Spring WebFlux framework. The major advantage of this API is that the developer doesn’t have to worry about concurrency or threads. WebClient takes care of that.

WebClient has a built-in HTTP Client library support to perform requests with. That includes Apache HttpComponents, Jetty Reactive HttpClient, or Reactor Netty.

WebClient.builder() offers following options:

  • uriBuilderFactory – customized uriBuilderFactory to use base URL
  • defaultHeader – Headers for every request
  • defaultCookie – Cookies for every request
  • defaultRequest – To customize every request
  • filter – Client filter for every request
  • exchangeStrategies – HTTP Message reader/writer customizations

I already showed retrieve method in the above code demo.

WebClient also offers a method exchange with varients like exchangeToMono and exchangeToFlux.

With attribute(), we can also add attributes to the request.

Alternatively, one can use WebClient for synchronous use also. In my example above MainController, I use block to get the final result. This basically blocks parallel calls till we get the result.

One key feature that WebClient offers is retryWhen(). For more resilient system, it is a great feature that you can add while using WebClient.

        webClient
            .get()
            .uri(String.join("", "/users", id))
            .retrieve()
            .bodyToMono(UserDto.class)
            .retryWhen(Retry.fixedDelay(5, Duration.ofMillis(100)))
            .block();

retryWhen takes Retry class as a parameter.

WebClient also offers a feature for error handling. doOnError() allows you to handle the error. It is triggered when mono ends with an error. onErrorResume() is a fallback based on the error.

Conclusion

In this post, I showed what is Spring WebClient is, how we can use Spring WebClient vs RestTemplate, and what different features it offers.

If you enjoyed this post, you can subscribe to my blog here.

References

  1. Spring WebClient – Spring Documentation
  2. WebClient Cheatsheet – Spring WebClient

The Complete Guide to Use Docker Compose

In this post, I will cover the complete guide to using docker compose. You can use it to build a multi-container application. But what is a docker compose and why one should use it?

What is Docker Compose?

If you don’t know what a docker is, you can read about that here. If you have an application that is running on a docker and if that application is using multiple other services like database, web-server, and load balancer, then you can write multiple docker files and run multiple containers. It can be cumbersome to manage these files. And if you have to change something, you might have to change all files.

Docker compose solves this problem by allowing you to write a YAML file to define multiple containers in a single file. You write one docker file and build and run that file for all the containers.

Installing Docker Compose

Based on the definition from docker.com, docker compose is a tool for defining and running multiple Docker containers.

Depending on your environment, you will have to use the instructions to install docker compose. You will also need docker engine before you can install docker compose. I use the Windows environment, so I will show those instructions here.

  • Launch Power shell in administrator mode
  • Run this command – [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
  • Then run the following command – Invoke-WebRequest “https://github.com/docker/compose/releases/download/1.27.4/docker-compose-Windows-x86_64.exe” -UseBasicParsing -OutFile $Env:ProgramFiles\Docker\docker-compose.exe

This will install docker compose. Open a new command prompt and type the first command

docker-compose -v

This should provide the docker-compose version if your installation has run without any issues.

Setting up a Spring Boot application with Docker

To show the power of docker-compose, we will be using a simple To-Do list spring boot app. I will share this app in a GitHub repository along with docker compose file. But this app includes the following applications that we will be using in docker compose:

  1. Spring Boot application
  2. Java version 8
  3. MySQL for database
  4. Keycloak for Authentication

So I won’t show implementing the Spring Boot application. If you want to download this application, you can visit the github repository or you can read my previous post here.

We will create a docker file for this Spring Boot application and this will run in its own container. Now this application connects to Keycloak and MySQL database for authentication. Keycloak will use Postgres database instead of using the same MySQL database.

The docker file for the Spring Boot application will look like below:

FROM openjdk:8-jdk-alpine
VOLUME /tmp
COPY ./build/libs/*.jar app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]

This docker file basically downloads Open JDK 8. It mounts the disk at /tmp. It copies an application jar file as app.jar. And of course, it will start the application by running java -jar .

How to write Docker Compose file

Now comes the docker-compose.yml file. This will look like below:

version: "3.8"

services:
  web:
    build: .
    ports:
      - "8080:8080"
    depends_on:
      - db
      - keycloak
    environment:
      SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/todolist?autoReconnect=true&useSSL=false
      SPRING_DATASOURCE_USERNAME: betterjavacode
      SPRING_DATASOURCE_PASSWORD: betterjavacode
      KEYCLOAK_URI: http://keycloak:8180/auth
      REALM: SpringBootKeycloakApp
    networks:
      - common-network
  db:
    image: mysql:5.7
    ports:
      - "3307:3306"
    restart: always
    environment:
      MYSQL_DATABASE: todolist
      MYSQL_USER: betterjavacode
      MYSQL_PASSWORD: betterjavacode
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - db-data:/var/lib/mysql
    networks:
      - common-network
  postgres:
    image: postgres
    volumes:
      - postgres_data:/var/lib/postgresql/data
    environment:
      POSTGRES_DB: keycloak
      POSTGRES_USER: keycloak
      POSTGRES_PASSWORD: password
    networks:
      - common-network
  keycloak:
    image: jboss/keycloak
    ports:
      - "8180:8180"
    command: ["-Djboss.socket.binding.port-offset=100"]
    environment:
      DB_VENDOR: POSTGRES
      DB_ADDR: postgres
      DB_DATABASE: keycloak
      DB_USER: keycloak
      DB_PASSWORD: password
      DB_SCHEMA: public
      KEYCLOAK_USER: admin
      KEYCLOAK_PASSWORD: Pa55w0rd
    depends_on:
      - postgres
    networks:
      - common-network
networks:
  common-network:
    driver: bridge
volumes:
  db-data:
    driver: local
  postgres_data:
    driver: local

The first line in this docker-compose file is the version of your docker-compose.

services define different types of services that we will use to build our docker container. web service uses an image that builds from a docker file. In our case, we are building a docker image of our Spring Boot application. This application will run on port 8080. We also have to make sure to pass the required environment variables. As you see in the file, we are using our database as db and the variable SPRING_DATASOURCE_URL shows that. db is the name of our database service that our application will connect to.

Our database service db runs on host port of 3307, but uses port 3306 (default port) on the container. This is because I have MySQL running on my host machine at port 3306, so to avoid port conflict, I am using 3307.

We have another database service postgres in our docker compose file. That uses default ports of 5432 and that’s why not specified here. Keycloak uses postgres as part of this entire application. If you don’t specify postgres, Keycloak will use an in-memory H2 database by default. The problem with an in-memory database is once you stop your container, it will lose all the data. To avoid that, I am using a real database that will save our realm and users’ data.

Another service, that we are using is keycloak. This is our IDP for authentication. The service is running on port 8180. It uses the Postgres database to connect. The command part of keycloak service instructs to run the service on port 8180 in the container instead of default 8080.

networks service defines that all these containers are part of the same network common-network with a driver of type bridge.
To make sure we can use the database, we need to mount the disk volume for both MySQL and Postgres databases. We mount these volumes locally.

Running the containers

Now to execute the containers with the application, execute the following command (make sure you build your application)

docker-compose up

This will build Docker containers for all our services and start them. Now if we access our application at http://localhost:8080

Fundamentals of Docker Compose

If a user clicks on Get all tasks, user will see keycloak login screen as below:

Fundamentals of Docker Compose

Enter the username and password, and the user will see the tasks for the logged-in user.

Docker Compose Guide

Useful commands

docker-compose up – This command will build the docker containers and start them.

docker-compose up -d – This is a similar command as above, except it will run all the processes in the background.

docker-compose stop – Stop the docker services. This will retain the previous state of containers even after you have stopped the containers.

docker-compose start – Start the docker services

docker-compose logs – Show the logs from docker containers

docker-compose ps – List the Docker containers

docker-compose run – Run one-off command. Example – docker-compose run web env – List the environment variables of web service.

Advantages of Docker Compose

  • By running most of the services in docker, you don’t have to install those services in your environment.
  • It’s easier to collaborate on the development environment with other developers by checking in the source in version control with docker-compose.
  • Quick and easy configuration. You can run your services across platforms.

Advance use of docker compose

Something I have not covered in this post is using network as  a service that you can really extend with docker compose. It also allows you to run a load balancer (or reverse proxy-like nginx) and manage the load with multiple hosts.

Instead of using environment variables, you can also use .env file for environment variables and load it while starting the containers.

Conclusion

In this post, I showed how you can use docker compose to run multiple containers with a single docker compose file. It also allows you to easily manage your environment. Similarly, you can learn about Kubernetes.

References

  1. Docker Compose – docker compose
  2. Keycloak – Keycloak containers

Fundamentals of a Distributed System Design

When you are a beginner software developer, your focus is on the micro-level. What happens in your code? What happens in your application? But if you start thinking in a System Design way, it can help you immensely in your career. System design is a big topic, but I will cover the important fundamentals of distributed system design. Understanding System Design is the key to building a good system. Therefore, a developer should definitely try to learn about system design.

Fundamentals of a Distributed System

In this post, we will learn the following fundamentals.

  1. Key characteristics of a distributed system
  2. Load balancing
  3. Caching
  4. Database
  5. Database indexes
  6. Proxies
  7. CAP Theorem
  8. Consistent Hashing

Key Characteristics of a distributed system

Scalability

  • Scalability is the system’s ability to grow and manage increased demand
  • Horizontal scaling – you scale by adding more servers into your pool of resources.
  • Vertical scaling – you scale by adding more power to an existing server.

Reliability

  • It is the probability a system will fail in a given period. Specifically, the goal is to minimize this probability as much as possible.
  • To achieve reliability, redundancy is required. Therefore, it has a cost.

Availability

  • Availability is the time a system remains operational to perform its required function in a specific period.
  • If a system is reliable, it is available. By comparison, if it is available, it is not necessarily reliable.

Efficiency

  • Latency – response time
  • Throughput – the number of items delivered in a given time unit

Load Balancing

The load balancer routes the traffic from clients to different servers. It keeps track of the status of all the resources while distributing requests. Equally, a load balancer reduces individual server load and prevents any one application server from becoming a single point of failure. So, the load balancer can be added between clients and web servers, between webservers and an internal platform layer (application server), and between internal platform and database servers.

To organize a load balancer for distributing requests to servers, one can use different algorithms like Round Robin, Weighted Round Robin, Least Connection Method, Least Response Time, Least Bandwidth, IP Hash.

As a result, the load balancer can be a single point of failure. To overcome this, a second load balancer can be connected to the first to form a cluster.

Caching

Caches take advantage of the locality of references principle. A cache is like a short term memory. That is to say, it is faster with limited space. Furthermore, caches can exist at all levels in the architecture but often found at the level nearest to the front end.

Application Server Cache

Placing a cache directly on a request layer node enables the local storage of response data.

Content Distribution Network

CDNs are a kind of cache that comes into play for sites serving large amounts of static data.

Cache Invalidation

  1. Write through cache – Write the data into the cache and the corresponding database at the same time.
  2. Write around cache – Write the data to permanent storage, bypassing the cache. Therefore, recently written data will create a cache miss.
  3. Write-back cache – Write the data to cache alone and sync with backend storage after a specified interval.

Cache Eviction Policies

  1. First In First Out
  2. Last In First Out
  3. Least Recently Used
  4. Least Frequently Used
  5. Most Recently Used
  6. Random Replacement

Database

You will need a storage system for your data. Obviously, Databases are the most common solution. Accordingly, there are two types of databases. Basically, Relational databases and Non-Relational databases.

If your data is structured, you can use a relational database. Also, relational databases offer structured query language (SQL) to query the databases.

Non-relational databases are unstructured, and distributed.

SQL

  1. Store data in rows and columns
  2. Each row contains information about one entity
  3. MySQL, MS SQL, Oracle, PostgreSQL, SQLite are some examples of relational databases.
  4. SQL databases use SQL for querying.
  5. Vertically scalable, but expensive.
  6. Horizontally scalable, but time-consuming process.
  7. SQL databases are ACID (Atomicity, Consistency, Isolation, and Durability) compliant.
  8. If you need ACID compliance and structured data, use SQL databases.

NoSQL

  1. Key-Value Stores  – Redis, Dynamo DB
  2. Document databases – Couch DB and MongoDB
  3. Wide-Column databases – Columnar databases are best suited for analyzing large datasets – Cassandra and HBase
  4. Graph databases – data stored and related to each other in graph format.  Subsequently, data is stored with nodes (entities), properties (info about entities), and lines (the connection between entities) – Neo4J and InfiniteGraph
  5. Schemas are dynamic. Columns can be added on the fly and each row doesn’t have to contain data for each column.
  6. Use UnQL (Unstructured Query Language).
  7. Horizontally scalable easily.
  8. Not ACID Compliant
  9. Allows rapid development, stores a large volume of data with no structure.

Database Indexes

If the database search performance has been bad, we create indexes to improve that performance. Henceforth, the goal of creating an index on a particular table in a database is to make it faster to search through the table.

Indexes improve read performance, but decrease write performance. Consequently, indexes also increase memory usage. If your database is read-intensive, indexes are a good strategy. Don’t add indexes if the database is write-intensive.

Proxies

Proxy server is a piece of software or hardware that acts as an intermediary for requests from clients seekings resources from other servers. Accordingly, Proxies are used to filter requests, log requests, and sometimes transform the requests. Even more, proxy server cache can serve a lot of requests.

Open Proxy

An open proxy server is accessible by any internet user. As a result, any internet user is able to use the proxy for forwarding the requests.

Reverse Proxy

A reverse proxy retrieves resources on behalf of the client from one or more servers. Consequently, these resources are then returned to the client.

CAP Theorem

In any distributed system, you can not achieve all three consistency, availability, and partition tolerance.

CAP Theorem states that you can only get two out of these three options.

Consistency – All nodes see the same data at the same time.

Availability – Every request gets a response on success/failure.

Partition Tolerance – A partition tolerant system can tolerate any amount of network failure that doesn’t result in a failure of the entire network. Particularly, data replication across nodes helps to keep the system up.

Consistent Hashing

Consistent hashing is a mechanism that allows distributing the data across a cluster in such a way that will minimize reorganization when nodes are added or removed. As a result, when you employ consistent hashing, resizing of the hash table results in the remapping of k/n keys.

Conclusion

In conclusion, knowing these fundamentals about a distributed system can immensely help a developer while writing code or designing a system. By all means, study these fundamentals, but you should also learn about domain-driven design. Nonetheless, if you enjoyed this post, you can subscribe to my blog here.

References

  1. System Design Primer – System Design Primer
  2. System Design – System Design

The Definitive Guide to Use Keycloak With a Spring Boot Application

In this post, I will show how to use Keycloak in a Spring Boot application. Before we use Keycloak, we will cover some basics about what Keycloak is and why we use it.

To get started with this demo, you will need the following things:

  • A Code Editor – IntelliJ
  • Database – MySQL
  • Keycloak
  • Java 8

What is Keycloak?

Keycloak is an open-source identity and access management solution for modern applications and services. Keycloak provides both SAML and OpenID protocol solutions.

Why do we use Keycloak?

As mentioned, Keycloak provides identity and access management, it is also open source. SAML and OpenID protocols are industry standards. Building an application that is integrated with Keycloak will only provide you a more secure and stable solution. There are definitely other solutions available like Gluu, Shibboleth, WSO2, and Okta.

For this post, we will be using Keycloak.

Securing Spring Boot Application with Keycloak

There are two parts to this demo. One is about Keycloak. The second is about securing the Spring Boot Application with Keycloak.

Install Keycloak

Download the keycloak on your machine.  Unzip the downloaded file and run the server with the following command from bin directory on your command prompt (Note – I’m on a windows machine):

standalone.bat -Djboss.socket.binding.port-offset=100

This will start the Wildfly server for your Keycloak on your local machine. We can access the server by executing the URL http://localhost:8180. If you just use standalone.bat to execute without that parameter, the server will run on the port 8080.

Spring Boot Application with Keycloak

Once you start the server, the first thing you will have to do is to create an admin user. We will create a user admin and password d#n3q2b .

Now we will access the administration console and enter our user details. Once we login as an admin user, we will see the first screen as below:

Keycloak Home Screen

Adding application

Initial screens shows the default realm. For our demo purposes, we will create a new realm SpringBootKeycloakApp . In this realm, we will add our Spring Boot application as a client. Create a new client on Clients tab. We will name our client application as SpringBootApp.

Now in settings, we will add redirect url for our Spring Boot Application. This is the URL where Keycloak will redirect to our app after authentication. Also, we are using openid connect as a protocol as part of this implementation.

Keycloak with Spring Boot App

Adding user

Now we will add a user that we will use to authenticate. We will use this user to login to our sample Spring Boot application.

Add a role that you want for this user ROLE_User on the roles tab in Keycloak. Once that is done, let’s go to the Users tab and add a new user.

Keycloak: add user

On the Role Mappings tab, make sure to add the newly created role for this user.

Create A Spring Boot Application

Now, we will create a simple Spring Boot application that will use Keycloak for security. As part of this application, we will be showing a list of to-do list tasks for the user who will authenticate with the application.

To build this app, we need the following dependencies:


dependencies {
 implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
 implementation 'org.springframework.boot:spring-boot-starter-security'
 implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
 implementation 'org.springframework.boot:spring-boot-starter-web'
 implementation 'org.springframework.boot:spring-boot-starter-jdbc'
 implementation 'org.keycloak:keycloak-spring-boot-starter'
 runtimeOnly 'mysql:mysql-connector-java'
 testImplementation('org.springframework.boot:spring-boot-starter-test') {
  exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
 }
 testImplementation 'org.springframework.security:spring-security-test'
}

As you can see we are using spring-boot and spring-security along with keycloak-spring-boot-starter dependency.

The keycloak dependency includes Keycloak client adapters. We will use these adapters for authentication purposes. They will replace our standard Spring Security adapters. To make sure this keycloak-spring-boot-starter dependency works correctly, we will need one more dependency to be added in our gradle file as below:


dependencyManagement {
 imports {
  mavenBom "org.keycloak.bom:keycloak-adapter-bom:11.0.2"
 }
}

To read more about this, you can visit the official documentation of keycloak.

Our Controller class will have two important methods, one to get the home page which will be accessible for anyone, and another to get the list of tasks that will be accessible to only authenticated users with a role ROLE_User.  The code for this TaskController will look like below:


package com.betterjavacode.keycloakdemo.keycloakdemo.controllers;

import com.betterjavacode.keycloakdemo.keycloakdemo.dto.TaskDto;
import com.betterjavacode.keycloakdemo.keycloakdemo.managers.TaskManager;
import org.keycloak.KeycloakSecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class TaskController
{
    private final HttpServletRequest request;

    @Autowired
    public TaskController(HttpServletRequest request)
    {
        this.request = request;
    }

    @Autowired
    private TaskManager taskManager;

    @GetMapping(value="/")
    public String home()
    {
        return "index";
    }

    @GetMapping(value="/tasks")
    public String getTasks(Model model)
    {
        List tasks = taskManager.getAllTasks();
        model.addAttribute("tasks", tasks);
        model.addAttribute("name", getKeycloakSecurityContext().getIdToken().getGivenName());

        return "tasks";
    }

    private KeycloakSecurityContext getKeycloakSecurityContext()
    {
        return (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    }

}

In this controller class, we use TaskManager to get all tasks. I will explain  KeyCloakSecurityContext when I will show about SecurityConfig.

With or without Spring-Security

We can leverage this application and use Keycloak for authentication with or without Spring-Security. As part of this demo, we are using Spring-Security. To use the same application without Spring-Security, you can just remove the Spring-Security dependency and add security configuration through application.properties file.

We will need the following properties in application.properties to use Keycloak for authentication in this app.

keycloak.auth-server-url=http://localhost:8180/auth
keycloak.realm=SpringBootKeycloakApp
keycloak.resource=SpringBootApp
keycloak.public-client=true
keycloak.principal-attribute=preferred_username

If we wanted to use this application without Spring-Security, we will need the following two properties also:

keycloak.security-constraints[0].authRoles[0]=ROLE_User
keycloak.security-constraints[0].securityCollections[0].patterns[0]=/tasks

Since we are using Spring-Security, we will configure the security configuration through a Java class SecurityConfig.

This SecurityConfig class will extend KeyCloakWebSecurityConfigurerAdapter .

Our configure method will look like below:

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        super.configure(httpSecurity);
        httpSecurity.authorizeRequests()
                .antMatchers("/tasks").hasRole("User")
                .anyRequest().permitAll();
    }

Basically, any requests coming to /tasks endpoint, should have user role as ROLE_User. The prefix of ROLE_ is assumed here. Other than any other request will be permitted without any authorization. In this case, we will be calling our index page.

We will be using annotation @KeyCloakConfiguration which is basically covers @Configuration and @EnableWebSecurity annotations.

Since our SecurityConfig extends KeycloakWebSecurityConfigurerAdapter, we have to implement sessionAuthenticationStrategy and httpSessionManager. We will also have to register our idp Keycloak with Spring Security Authentication Manager.

So our SecurityConfig will look like below:


package com.betterjavacode.keycloakdemo.keycloakdemo.config;

import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.keycloak.adapters.springsecurity.management.HttpSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;


@KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter
{
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder)
    {
        SimpleAuthorityMapper simpleAuthorityMapper = new SimpleAuthorityMapper();
        simpleAuthorityMapper.setPrefix("ROLE_");

        KeycloakAuthenticationProvider keycloakAuthenticationProvider =
                keycloakAuthenticationProvider();
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(simpleAuthorityMapper);
        authenticationManagerBuilder.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy ()
    {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Bean
    @Override
    @ConditionalOnMissingBean(HttpSessionManager.class)
    protected HttpSessionManager httpSessionManager()
    {
        return new HttpSessionManager();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        super.configure(httpSecurity);
        httpSecurity.authorizeRequests()
                .antMatchers("/tasks").hasRole("User")
                .anyRequest().permitAll();
    }
}

So Spring Security uses roles in upper case like ROLE_USER and always use ROLE_ prefix. To handle that, I have added a user with a role ROLE_User in Keycloak, but we will only verify a prefix as our http configuration will verify the role anyhow.

Since we will be authenticating with Keycloak, we will need a session for user’s state. We are using RegisterSessionAuthenticationStrategy here. HttpSessionManager is a conditional bean because Keycloak already implements that bean.

To implement the Keycloak Spring Boot adapter, we will add a KeyCloakSpringBootConfigResolver bean as follows:


package com.betterjavacode.keycloakdemo.keycloakdemo.config;

import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class KeycloakConfig
{
    @Bean
    public KeycloakSpringBootConfigResolver keycloakSpringBootConfigResolver()
    {
        return new KeycloakSpringBootConfigResolver();
    }
}

I have not shown the rest of the application build, but the code is available on GitHub for this project.

Demo of the application

Run our keycloak application, it will be running on http://localhost:8180. Our Spring Boot application will be running at http://localhost:8080.

Our first screen of the Spring Boot application will look like below:

Spring Boot Application with Keycloak

Now if a user clicks on Get all tasks, he will be redirected to Keycloak login screen as below:

Securing Spring Boot App with Keycloak

Now, I will enter my user betterjavacode username and password and it will show us our list of tasks as follows:

Spring Boot Application and Keycloak

 

Authentication Flow

When the user clicks on Get all tasks, the user is redirected to Spring Security‘s sso/login endpoint which KeycloakSpringBootConfigResolver handles and sends an authorization code flow request to Keycloak

http://localhost:8180/auth/realms/SpringBootKeycloakApp/protocol/openid-connect/auth?response_type=code&client_id=SpringBootApp&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fsso%2Flogin&state=70bd4e28-89e6-43b8-8bea-94c6d057a5cf&login=true&scope=openid

Keycloak will process the request to respond with a session code and show the login screen.

Once the user enters credentials and keycloak validates those, it will respond with an authorization code, and this code is exchanged for a token, and the user is logged in.

Conclusion

In this post, I showed how to secure your Spring Boot application using Keycloak as an identity provider. If you enjoyed this post, please consider subscribing to my blog here.

References

  1. Keycloak – Keycloak
  2. Securing your application with Keycloak – Secure your application

Json Web Token: How to Secure Spring Boot REST API

In this post, I will show how to secure your spring boot based REST API. It has been more of a trend to secure REST APIs to avoid any unnecessary calls to public APIs. We will be using some Spring boot features for Spring security along with JSON WebTokens for authorization. You can learn more about basic authentication here.

User flow in this case is

  1. User logs in
  2. We validate user credentials
  3. A token is sent back to user agent.
  4. User tries to access a protected resource.
  5. User sends JWT when accessing the protected resource. We validate JWT.
  6. If JWT is valid, we allow the user to access the resource.

JSON WebTokens, known as JWTs are used for forming authorization for users. This helps us to build secure APIs and it is also easy to scale. During authentication, a JSON web token is returned. Whenever the user wants to access a protected resource, the browser must send JWTs in the Authorization header along with the request. One thing to understand here is that it is a good security practice to secure REST API.

Basically, we will show

  1. Verify JSON WebToken
  2. Validate the signature
  3. Check the client permissions

What you will need?

  1. Java 8,
  2. MySQL Database
  3. IntelliJ Editor
  4. Gradle

Note – This won’t be a full-fledged app, but REST APIs based on Spring Boot, and Spring security.

Spring Boot Based REST API

Since I have already shown this before on my blog, I won’t be creating any new APIs. I will be securing REST API for company that I created in this blog post REST API. This API also includes caching. A user will try to access /cachedemo/v1/companies/ and since APIs are protected, he will get a response like below:

Secure REST API - Forbidden

Response from protected API

Now we will implement how to protect this API and how to access it.

Adding User and User Registration

Since we want to add authorization for APIs, we will need where the user is able to log in and send credentials. These credentials will be validated and a token will be generated. This token then will be transmitted in a request to an API call. The token will be validated in the Spring security authorization filter that we will add. If a valid token, the user will be able to access the API.

Create a user model


package com.betterjavacode.models;

import javax.persistence.*;
import java.io.Serializable;

@Entity(name = "User")
@Table(name = "user")
public class User implements Serializable
{
    public User()
    {

    }

    @Id
    @GeneratedValue(strategy =  GenerationType.IDENTITY)
    private long id;

    @Column(name = "username")
    private String username;

    @Column(name = "password")
    private String password;

    public long getId()
    {
        return id;
    }

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

    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;
    }
}

We will add a controller where a user can register with its details for username and password.


package com.betterjavacode.resources;

import com.betterjavacode.models.User;
import com.betterjavacode.repositories.UserRepository;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
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;

@RestController
@RequestMapping(value = "/cachedemo/v1/users")
public class UserController
{
    private UserRepository userRepository;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public UserController(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder)
    {
        this.userRepository = userRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @PostMapping("/signup")
    public void signUp(@RequestBody User user)
    {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }

}

Now when we POST a request to /cachedemo/v1/users/signup , a user will be saved in the database. Password for the user will be saved in encrypted format as we are using BCryptPasswordEncoder. We will show how a user can log in to create a token.

User Login

To handle user login, we will add an AuthenticationFilter which will get added in FilterChain and Spring boot will handle the execution of it appropriately. This filter will look like below:


package com.betterjavacode.SpringAppCache;


import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter
{
    private AuthenticationManager authenticationManager;

    public AuthenticationFilter(AuthenticationManager authenticationManager)
    {
        this.authenticationManager = authenticationManager;
        setFilterProcessesUrl("/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException
    {
        try
        {
            com.betterjavacode.models.User creds = new ObjectMapper().readValue(request.getInputStream(), com.betterjavacode .models.User.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(creds.getUsername(), creds.getPassword(),new ArrayList<>()));
        }
        catch(IOException e)
        {
            throw new RuntimeException("Could not read request" + e);
        }
    }

    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, Authentication authentication)
    {
        String token = Jwts.builder()
                .setSubject(((User) authentication.getPrincipal()).getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + 864_000_000))
                .signWith(SignatureAlgorithm.HS512, "SecretKeyToGenJWTs".getBytes())
                .compact();
        response.addHeader("Authorization","Bearer " + token);
    }
}

Basically, a user will send credentials in a request to URL ending with /login . This filter will help to authenticate the user, if there is successful authentication, a Token will be added in response header with the key Authorization.

Token Validation and Authorization

We add another filter AuthorizationFilter to validate the token that we passed through AuthenticationFilter earlier. This filter will look like below:


package com.betterjavacode.SpringAppCache;

import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

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


public class AuthorizationFilter extends BasicAuthenticationFilter
{
    public AuthorizationFilter(AuthenticationManager authenticationManager)
    {
        super(authenticationManager);
    }

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException
    {
        String header = request.getHeader("Authorization");
        if(header == null || !header.startsWith("Bearer"))
        {
            filterChain.doFilter(request,response);
            return;
        }

        UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(request);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request)
    {
        String token = request.getHeader("Authorization");
        if(token != null)
        {
            String user = Jwts.parser().setSigningKey("SecretKeyToGenJWTs".getBytes())
                    .parseClaimsJws(token.replace("Bearer",""))
                    .getBody()
                    .getSubject();
            if(user != null)
            {
                return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
            }
            return null;
        }
        return null;
    }
}

If the validation of the token is successful, the application returns a user and assigns it to a security context.

To enable Spring security, we will add a new class WebSecurityConfiguration with annotation @EnableWebSecurity. This class will extend the standard WebSecurityConfigurerAdapter . In this class, we will restrict our APIs and also add some whitelisted URLs that we will need to access without any authorization token. This will look like below:


package com.betterjavacode.SpringAppCache;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter
{
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    private UserDetailsService userDetailsService;

    private static final String[] AUTH_WHITELIST = {
            "/v2/api-docs",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**"
    };

    public WebSecurityConfiguration(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder)
    {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
        this.userDetailsService = userDetailsService;
    }


    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(AUTH_WHITELIST).permitAll()
                .antMatchers(HttpMethod.POST, "/cachedemo/v1/users/signup").permitAll()
                .anyRequest().authenticated()
                .and().addFilter(new AuthenticationFilter(authenticationManager()))
                .addFilter(new AuthorizationFilter(authenticationManager()))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception
    {
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource()
    {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}

In method configure we have restricted most APIs, only allowing Swagger URLs and signup URL. We also add filters to HttpSecurity. We will add our own UserDetailsServiceImpl class to validate user credentials.


package com.betterjavacode.services;

import com.betterjavacode.models.User;
import com.betterjavacode.repositories.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class UserDetailsServiceImpl implements UserDetailsService
{
    private UserRepository userRepository;

    public UserDetailsServiceImpl(UserRepository userRepository)
    {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        User user = userRepository.findByUsername(username);
        if(user == null)
        {
            throw new UsernameNotFoundException(username);
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), Collections.emptyList());
    }
}

Demo

With all the code changes, now we are ready to create a user, login and access secured REST APIs. From the image above, a user gets Access Denied error for accessing secured APIs. To demo this, I have already registered a user with username `test1` and password test@123.

Secure REST API - send use credentials to login

This POST request will give us Authorization token in response as shown above. Now using this token in our GET request to retrieve companies data. This GET request will look like below:

Secure REST API - Postman call

In this way, we showed how to secure REST API using JSON web token.

I will be launching the book “Simplifying Spring Security“. Do you want to get updates on launch? Sign up

References

  1. Implementing JWTs Authentication on Spring Boot API – JWT Authentication
  2. How to secure REST APIs – Secure REST APIs