Secure your Spring Boot API with JSON Web Tokens

Secure your Spring Boot API with JSON Web Tokens


If you are reading this article I assume you are a bit familiar with Spring Boot and building API using it. Because the main purpose of this article is to show you a simple way how to make your API more secured.

But before we get started I want to be sure that all of you have some basic knowledge of JSON Web Tokens (JWT). So here is the link to the official website where you can dive deeper into JWT theory.

The official definition of JWT sounds like this:

From history

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.


Let’s proceed to a practice part. I’ve created a new maven project and my pom.xml file contains the following dependencies:








            <!-- Package as an executable jar/war -->


As you noticed we will be using MongoDB as database; jackson-databing for binding request and response data into JSON format; lombok for generating getters, setters etc.

Let’s create application.yml in the resources folder and add the following content:

      database: springjwt
      host: localhost
      port: 27017
        enabled: true

Next we need to create some default package, I will call it com.jwt.example and add main class which will be responsible for starting our Spring Boot application. I will call it Application, but you can give it any name you like.

public class Application {
    public static void main(String[] args) throws Exception {, args);

If you did everything right then our appllication should be started successfully. But it does not do anything yet, so let’s continue and add some more packages into our default package: configuration, controller, model, repository, service.

In the model package add simple User class with following content:

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    private ObjectId id;
    private String name;
    private String email;
    private String password;

All annotations that you can see is added from lombok package that was mentioned before. User needs to be saved and fetched from database, so let’s add UserRepository interface which extends MongoRepository. We will not add any methods to this interface because MongoRepository already have built-in all CRUD operations.

public interface UserRepository extends MongoRepository<User, 
ObjectId> {

Next thing we need to do is to add UserService class with two methods saveUser and getUser.

public class UserService {

private UserRepository userRepository;
private TokenService tokenService;

UserService(UserRepository userRepository, TokenService tokenService) {
this.userRepository = userRepository;
this.tokenService = tokenService;

public User getUser(ObjectId userId) {
return userRepository.findOne(userId);

public String saveUser(User user) {
User savedUser =;
return tokenService.createToken(savedUser.getId());

These two methods are pretty simple. GetUser() just finds user in database using injected userRepository class. SaveUser() saves user to database. NOTE: saving user’s password without hashing it is a bad practice, I just skipped it because it’s not a scope of this topic. After saving user we create a token by calling tokenSerice.createToken() method. TokenService is not in our project yet, so I will add it into service package:

public class TokenService {

public static final String TOKEN_SECRET = "s4T2zOIWHMM1sxq";

public String createToken(ObjectId userId) {
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
String token = JWT.create()
.withClaim("userId", userId.toString())
.withClaim("createdAt", new Date())
return token;
} catch (UnsupportedEncodingException exception) {
//log WRONG Encoding message
} catch (JWTCreationException exception) {
//log Token Signing Failed
return null;

public String getUserIdFromToken(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm)
DecodedJWT jwt = verifier.verify(token);
return jwt.getClaim("userId").asString();
} catch (UnsupportedEncodingException exception) {
//log WRONG Encoding message
return null;
} catch (JWTVerificationException exception) {
//log Token Verification Failed
return null;

public boolean isTokenValid(String token) {
String userId = this.getUserIdFromToken(token);
return userId != null;

TokenService is a class where all stuff related to JWT is happening. Let me explain some parts of this code.

Get a line on how to increase app performance with Hazelcast – our article is ready for reading.

TOKEN_SECRET is a random generated string, you can use any string you like.

createToken() is main method which creates a token based on HMAC256 algorithm. As you can see I added userId into withClaim() method. This method let us to add any info into token and this data can be fetched from token after decoding it. You probably noticed that I added one more claim “createdAt” which is a Date object. This is done with one puprose — to make token string be different everytime. Because if you add only userId which is always the same for one user, token will be the same, so I added a Date object which is always unique at any moment of time. If token cannot be created for some reason then exception will be thrown.

isTokenValid() method just returns true or false if token is valid or not. It calls getUserIdFromToken() method which performs decoding of token with the same algorithm and token secret. If token is valid then decoder can pull userId from token in other case exception will be thrown and null will be returned.

We are almost done. One thing is left to do is to tell our Spring Application which routes (request mappings) should be used with token and which should be available for all users. To do this we need to create JWTFilter class that extends GenericFilterBean class and override method doFilter(). Also we need to add @Configuration annotation to this class. Let’s look into the code and I will explain what is going on here.

public class JWTFilter extends GenericFilterBean {

private TokenService tokenService;

JWTFilter() {
this.tokenService = new TokenService();

public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String token = request.getHeader("Authorization");

if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.sendError(HttpServletResponse.SC_OK, "success");

if (allowRequestWithoutToken(request)) {
filterChain.doFilter(req, res);
} else {
if (token == null || !tokenService.isTokenValid(token)) {
} else {
ObjectId userId = new ObjectId(tokenService.getUserIdFromToken(token));
request.setAttribute("userId", userId);
filterChain.doFilter(req, res);



public boolean allowRequestWithoutToken(HttpServletRequest request) 
if (request.getRequestURI().contains("/register")) {
return true;
return false;

Let’s go step by step through doFilter() method. First of all we are casting request and response to HttpServletRequest and HttpServletResponse to have access to some http methods. Then we get a token from “Authorization” header. As you may guess we will pass our token as Authorization header with each request that requires token. After that we check if request method is “OPTIONS” and if so we send success response. This is need because before sending request to some endpoint some browsers send OPTIONS request to be ensure that the request being done is trusted by the server.

By default all requests will be checked for Authorization header, so if we want to skip some routes we should explicitly declare these routes. For this purpose we have added a method allowRequestWithoutToken() where we added “/register” request mapping. So if we’re sending register new user request then method filterChain.doFilter(req, res) will be called. This method is proceeding to the next filter and the last filter in the chain will be our destination request mapping. As we don’t have any other filter then doFilter() method will directly go to our controller which we will add in a minute.

Next step in our doFilter method is checking if token is null or invalid. If so, then Unauthorized response will be sent. If token is valid we’re retrieving userId from token and adding it as an Attribute to the request object. After this we can get userId from attribute in any method in our controller.

Last step is adding our UserController class

public class UserController {

private UserService userService;

UserController(UserService userService) {
this.userService = userService;

public String regiterUser(@RequestBody User user) {
return userService.saveUser(user);

public User getUser(HttpServletRequest request) {
ObjectId userId = (ObjectId) request.getAttribute("userId");
return userService.getUser(userId);

Nothing special here, just calling userService methods, except getting userId from request attribute in getUser()method.

Congratulations! We are done. It’s time to test our API. Restart your Application and open Postman to send some request. Let’s create new user by sending POST request to https://localhost:8080/user/register with the following request body:

“name”: “Ihor Sokolyk”,
“email”: “”,
“password”: “password”

We should get a token in the response body:


Now copy this token and let’s try to get just created user by making GET request to https://localhost:8080/user/get, but do not forget to add our token as Authorization header:

Authorization header image

If you don’t pass token or remove some character from it then you should get 401 Unauthorized error:

Unauthorized error image


Conclusion. Now you know how to use JWT tokens and how to secure your API. But you can play around with it and make it more complicated, for example save all tokens to database and implement logging from different devices functionality.

Thank you for reading this article. If you have any questions or notes please feel free to leave a comment. You can check all sources on my GitHub. As well you can check it on Oril Software GitHub.





Spring Boot Profiles

How many times did you have to use different credentials or configuration in production and development applications? I bet your answer is ‘Every single time!’. The simplest example describing this is using payment systems in your application. In development mode you want to use test payments in order not to loose all off your money […]

Ihor Sokolyk Avatar
Ihor Sokolyk

25 May, 2018 · 3 min read

Uploading files to AWS S3 Bucket using Spring Boot

Account Configuration To start using S3 Bucket you need to create an account on Amazon website. Registration procedure is easy and clear enough, but you will have to verify your phone number and enter your credit card info (don’t worry, your card will not be charged if you only buy some services). After account creation […]

Ihor Sokolyk Avatar
Ihor Sokolyk

23 Nov, 2023 · 7 min read

Spring Boot + PayPal + Angular 2

Hi guys! Nowadays, more often and often in different projects you have to handle and deal with different payment services, like Stripe, PayPal,, etc, to provide users with ability to purchase in your app, or make payouts to them. Here we will speak about how to add PayPal payment system to the Spring Boot […]

Ihor Kosandyak Avatar
Ihor Kosandyak

8 Nov, 2017 · 6 min read