Secure your Spring Boot API with JSON Web Tokens

Ihor Sokolyk

7 Jun, 2021 · 3 min read

Overview

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.

Sources

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

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
    </parent>

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

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

        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.16</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.8</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <!-- Package as an executable jar/war -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>
    </build>

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:

spring:
  data:
    mongodb:
      database: springjwt
      host: localhost
      port: 27017
      repositories:
        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.

@SpringBootApplication
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, 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:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@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.

@Repository
public interface UserRepository extends MongoRepository<User, ObjectId> {
}

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

Conclusion

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.

No Article rating
0 Reviews
Was this article helpful? Please rate this article to give us valuable insights for our improvements.
  1. Wow!
  2. Mmm
  3. Hmm
  4. Meh
  5. hidden

#API

#Java

#Security

#SpringBoot

Table of Contents

Spring Cloud Gateway security with JWT

There is a clear understanding that everything that is exposed to the Internet should be secured. Especially when you create software and work with sensitive user data, such as emails, phone numbers, addresses, credit cards, etc. Here we will go through securing API Gateway with Json Web Tokens(JWT). As far as you probably know Spring […]

Ihor Kosandyak

26 Feb, 2021 · 4 min read

ORIL Front-end Digest (July 2020)

General How Emoji Can Improve Your Code—Seriously How to Become a Better Front-end Developer by Building Projects (Ideas Included) Keep Calm and Start Coding: How to Fight Coding Anxiety Javascript The Future Of JavaScript: Why It Is The Language Of The Next 10 Years How to Beat 5 Common JavaScript Interview Challenges Streamline Code Reviews […]

Volodymyr Padovskiy

17 Jul, 2020 · < 1 min read