Spring Boot Backend Development Course, Implementing Login and Logout with JWT, Adding Controllers

1. Introduction

Security is one of the most important factors in modern web applications. User authentication and authorization are key functions in maintaining this security.
In this course, we will take a detailed look at how to implement login and logout features using JWT (JSON Web Token) in backend development with Spring Boot.
This course covers the process of setting up a basic Spring Boot application, implementing a JWT-based authentication system, and adding a controller to complete the RESTful API.

2. What is Spring Boot?

Spring Boot is a tool that makes it easier to use the Java-based framework Spring.
This allows developers to minimize configuration and setup, enabling rapid application development.
Spring Boot can be packaged into a standalone JAR file and can efficiently develop RESTful services.
The main features of Spring Boot are as follows:

  • Auto-configuration: Spring Boot automatically configures the basic settings needed by developers.
  • Starter packages: Developers can use starter packages to quickly add the functionality they need.
  • Embedded server: Spring Boot provides embedded servers such as Tomcat, Jetty, and Undertow, making it easy to run applications.
  • Dependency management: Dependencies can be easily managed within the source code using Maven or Gradle.

3. What is JWT?

JWT (JSON Web Token) is an Internet standard RFC 7519 for secure information transmission. JWT uses a JSON object to encrypt and convey information such as subject (sub), issuer (iss), and expiration time (exp).
JWT is composed of three parts:

  1. Header: Specifies the type of JWT and the signing algorithm used.
  2. Payload: Contains the information to be transmitted and metadata describing that information.
  3. Signature: Secures the header and payload to prevent tampering. It is created using a secret key.

JWT is widely used for API authentication in high-traffic environments. It is efficient as there is no need to store sessions on the server, and it allows the client to hold state information,
reducing the load on the server.

4. Project Setup

4.1. Creating a Spring Boot Project

We use Spring Initializr to create a Spring Boot project.
Enter the necessary configurations as follows:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.6.6 (latest version)
  • Project Metadata:
    • Group: com.example
    • Artifact: jwt-demo
    • Name: jwt-demo
    • Description: JWT Authentication Demo
    • Packaging: Jar
    • Java: 11

Then, add the following dependencies:

  • Spring Web
  • Spring Security
  • Spring Data JPA
  • H2 Database
  • jjwt (Java JWT)

4.2. Project Structure

After creating the project, the basic package structure will be as follows:

    └── src
        └── main
            ├── java
            │   └── com
            │       └── example
            │           └── jwt_demo
            │               ├── JwtDemoApplication.java
            │               ├── controller
            │               ├── model
            │               ├── repository
            │               ├── security
            │               └── service
            └── resources
                ├── application.properties
                └── static
    

5. Database Configuration

We can use the H2 database to store user information.
Configure the application.properties file as follows:

    spring.h2.console.enabled=true
    spring.datasource.url=jdbc:h2:mem:testdb
    spring.datasource.driverClassName=org.h2.Driver
    spring.datasource.username=sa
    spring.datasource.password=
    spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
    

6. Creating a User Model

We create a User model class to hold user information.

    package com.example.jwt_demo.model;

    import javax.persistence.*;

    @Entity
    @Table(name = "users")
    public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;

        @Column(nullable = false, unique = true)
        private String username;

        @Column(nullable = false)
        private String password;

        // Getters and Setters...

        public User() {}

        public User(String username, String password) {
            this.username = username;
            this.password = password;
        }
    }
    

7. Creating a User Repository

We create a JPA repository interface to manage user information in the database.

    package com.example.jwt_demo.repository;

    import com.example.jwt_demo.model.User;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;

    @Repository
    public interface UserRepository extends JpaRepository {
        User findByUsername(String username);
    }
    

8. Security Configuration

We will implement JWT authentication through Spring Security. To do this, we create a SecurityConfig class that extends WebSecurityConfigurerAdapter.

    package com.example.jwt_demo.security;

    import com.example.jwt_demo.filter.JwtRequestFilter;
    import com.example.jwt_demo.service.UserDetailsServiceImpl;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.security.authentication.AuthenticationManager;
    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.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private UserDetailsServiceImpl userDetailsService;

        @Autowired
        private JwtRequestFilter jwtRequestFilter;

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

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/authenticate").permitAll()
                .anyRequest().

Spring Boot Backend Development Course, Implementing Login and Logout with JWT, Adding Dependencies

Hello! In this blog post, we will take a detailed look at how to implement login and logout functionalities using JSON Web Token (JWT) in the backend development process with Spring Boot. Authentication and authorization are crucial elements in web application development, and JWT helps to manage them effectively. In this tutorial, we will explain the concept of JWT, Spring Boot configuration, how to add dependencies, and more step by step.

1. What is JWT?

JWT stands for JSON Web Token, a standard for securely transmitting user authentication information. JWT consists of three parts:

  • Header: Contains information about the type of token and the hashing algorithm used.
  • Payload: Includes claims such as user information. This claim can contain public information (information needed for API calls).
  • Signature: A signature created using a secret key based on the header and payload information. This ensures the integrity of the data and is used to verify if someone has forged the token.

The greatest advantage of JWT is its stateless property. As there is no need for the server to maintain session state, it provides excellent scalability and performance.

2. Creating a Spring Boot Project

Let’s create a new project using Spring Boot. First, visit Spring Initializr (https://start.spring.io/). Apply the following settings to create the project:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.6.0 (select the latest version)
  • Group: com.example
  • Artifact: jwt-demo
  • Dependencies: Spring Web, Spring Security, Spring Data JPA, H2 Database

After creating the project, open it in your IDE and set up the necessary directory structure.

3. Adding Dependencies

First, add the required dependencies to the pom.xml file:

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jwt</artifactId>
    <version>0.9.1</version>
</dependency>

Additionally, Spring Security and Data JPA are already included, so no extra dependencies are needed. The H2 database can be useful for development and testing environments.

4. Configuring Spring Security

We need to configure Spring Security to use JWT. First, create the SecurityConfig class:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests().antMatchers("/api/auth/**").permitAll()
            .anyRequest().authenticated();
    }
}

In the above configuration, all users can access the /api/auth/** path. All other requests require authentication.

5. Generating and Validating JWT

Let’s write a class to generate and validate JWT. Define the necessary methods here:

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class JwtUtil {

    private String secretKey = "YourSecretKey"; // The secret key should be managed securely and not exposed

    public String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 10 hours
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }

    public boolean validateToken(String token, String username) {
        final String extractedUsername = extractUsername(token);
        return (extractedUsername.equals(username) && !isExpired(token));
    }

    public String extractUsername(String token) {
        return extractAllClaims(token).getSubject();
    }

    private Claims extractAllClaims(String token) {
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
    }

    private boolean isExpired(String token) {
        return extractAllClaims(token).getExpiration().before(new Date());
    }
}

The above JwtUtil class contains methods for token generation, validation, and username extraction.

6. Implementing Authentication and Logout

Now let’s write a controller to handle authentication and logout. Create the AuthController class:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public ResponseEntity login(@RequestBody AuthRequest authRequest) {
        // Add user authentication logic here
        String token = jwtUtil.generateToken(authRequest.getUsername());
        return ResponseEntity.ok(token);
    }

    @PostMapping("/logout")
    public ResponseEntity logout() {
        // Add logic to blacklist JWT, etc.
        return ResponseEntity.ok("Logout successful");
    }
}

In the above code, AuthRequest is a DTO class that contains the username and password, and the user authentication logic should be implemented in detail. Typically, it checks the authentication information in the database.

7. Final Testing

Now that we have completed all the configurations, you can test the API using a tool like Postman:

  • Login: POST /api/auth/login
  • Logout: POST /api/auth/logout

By passing the username and password in the request body of the login API, you will successfully receive a JWT in return. The returned JWT should be included in the Authorization header for subsequent API calls.

8. Conclusion

We explored the implementation of login and logout functionalities based on JWT using Spring Boot. Authentication and authorization are crucial aspects of web application development, and JWT helps manage these conveniently and securely. Additional features to consider include handling JWT blacklist and implementing refresh tokens.

I hope this tutorial has been helpful for your Spring Boot backend development. For more information and resources, you can check the official documentation and community. Thank you!

Spring Boot Backend Development Course, Implementing Login and Logout with JWT, Implementing Refresh Token Domain

In recent years, with the increasing popularity of microservices architecture and SPA (Single Page Application), it has become very important to find security measures for web applications. In this article, we will explain in detail how to implement login/logout functionality using JWT (JSON Web Token) and a domain that uses refresh tokens with Spring Boot.

Table of Contents

  1. 1. Introduction
  2. 2. What is Spring Boot?
  3. 3. What is JWT?
  4. 4. Setting Up the Development Environment
  5. 5. Implementing Login/Logout Functionality
  6. 6. Implementing Refresh Token
  7. 7. Conclusion

1. Introduction

User authentication and authorization are significant issues in modern web applications. Several technologies exist to address these issues, but JWT is one of the most widely used methods. In this course, you will learn how to build user login and logout functionalities using Spring Boot, as well as how to implement an authentication mechanism using JWT and refresh tokens.

2. What is Spring Boot?

Spring Boot is an extension of the Spring framework that provides convenient tools for developing Spring-based applications easily. It allows implementation without initial settings or complex XML configurations, providing pre-configured features that developers frequently use with simple annotations.

The main features of Spring Boot include:

  • Embedded Server: It includes web servers such as Tomcat and Jetty, allowing you to run without separate server installations.
  • Automatic Configuration: It automatically configures necessary settings based on included libraries and bean configurations in the project.
  • Easy Deployment: You can easily deploy by packaging into a Jar file and it can also be conveniently used in cloud environments.
  • Strong Community: It has a large community supported by rich documentation, examples, and various plugins.

3. What is JWT?

JWT (JSON Web Token) is a compact, URL-safe means of representing claims to be transferred between two parties, mainly used as a solution for authentication and authorization. Here, ‘claims’ refer to information about the user, which helps maintain a trust relationship between the server and the client.

JWT consists of three main parts:

  1. Header: Contains information about the type of token (typ) and hashing algorithm (alg).
  2. Payload: Contains information about the user and claim data, including user ID, permissions, etc.
  3. Signature: Combines Header and Payload, signing them with a secret key, which guarantees the integrity and authenticity of the token.

Advantages of JWT include:

  • Statelessness: Since the server cannot tamper with JWT, it does not maintain state, and the client sends JWT whenever authentication is required.
  • Security: Since the client holds the JWT, there is no need to query the server’s database, reducing the load on the database.
  • Simplified CRUD Operations: It allows easy management of authentication info and state, and can simplify complex logic like IAM (Identity and Access Management).

4. Setting Up the Development Environment

Now, let’s set up a development environment for a project using Spring Boot. We will use the following tools:

  • Java 11: Install JDK 11 or higher.
  • IDE: It is recommended to use IntelliJ IDEA or Eclipse.
  • Gradle or Maven: Choose Gradle or Maven for dependency management.
  • Postman: Use Postman as the API testing tool.

You can set the basic settings for your project using Spring Initializr (start.spring.io). The necessary dependencies to add include:

  • Spring Web
  • Spring Security
  • Spring Data JPA
  • H2 Database (or your chosen RDBMS)
  • Spring Boot DevTools (tools for development convenience)
  • jjwt (Java JWT library)

After creating the project, create necessary classes such as Viewer, Controller, Service, Repository, etc. You need to add database-related settings in the `application.yml` file.

5. Implementing Login/Logout Functionality

To implement login and logout functionalities, the following components are needed:

5.1. User Entity

Create a User entity to store user information.


@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;
    private String password;
    private String role;

    // Getter, Setter, Constructor
}

5.2. User Repository

Create a UserRepository to perform CRUD operations on the User entity.


@Repository
public interface UserRepository extends JpaRepository {
    Optional findByUsername(String username);
}

5.3. User Service

Create a UserService to implement user registration and authentication logic.


@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User register(User user) {
        // Add password encryption logic and save user information here.
    }

    public Optional findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
}

5.4. Security Configuration

Set up Spring Security to perform JWT authentication.


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // Define user authentication and security-related settings.
}

5.5. JWT Utility Class

Create a JwtUtil class responsible for generating and validating JWTs.


@Component
public class JwtUtil {
    private String secretKey = "yourSecretKey"; // Secret key must be managed securely.

    public String generateToken(String username) {
        // Implement JWT generation logic.
    }

    public boolean validateToken(String token, String username) {
        // JWT validation logic.
    }
}

5.6. Authentication Controller

Define API endpoints to provide login and logout functionalities.


@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody UserCredentials userCredentials) {
        // Login logic.
    }

    @PostMapping("/logout")
    public ResponseEntity<String> logout() {
        // Logout logic.
    }
}

6. Implementing Refresh Token

Refresh tokens are used separately from access tokens and help users remain logged in. To implement refresh tokens, we perform the following steps:

6.1. Refresh Token Entity

Create a new entity to manage the refresh token.


@Entity
public class RefreshToken {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String token;

    @ManyToOne
    private User user;

    private LocalDateTime expiryDate;

    // Getter, Setter, Constructor
}

6.2. RefreshToken Repository

Create a repository for performing CRUD operations on refresh tokens.


@Repository
public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> {
    Optional<RefreshToken> findByToken(String token);
}

6.3. Refresh Token Service

Create a service that manages the creation of refresh tokens.


@Service
public class RefreshTokenService {
    @Autowired
    private RefreshTokenRepository refreshTokenRepository;

    public RefreshToken createRefreshToken(User user) {
        // Logic for creating a new refresh token.
    }

    public boolean validateRefreshToken(String token) {
        // Validate the refresh token.
    }
}

6.4. Refresh Token Controller

Add an API to generate a new access token using the refresh token.


@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private RefreshTokenService refreshTokenService;

    @PostMapping("/refresh-token")
    public ResponseEntity<String> refreshToken(@RequestBody String refreshToken) {
        // Logic for generating a new access token using the refresh token.
    }
}

7. Conclusion

In this tutorial, we have implemented login/logout functionalities based on JWT using Spring Boot and additionally looked at how to manage access tokens using refresh tokens. An authentication system implemented in this way can handle various client requests more securely and flexibly.

Now you will be able to implement JWT and refresh tokens in your application to provide an enhanced user experience. Furthermore, you can integrate these technologies with various additional security techniques. We look forward to future advancements!

Spring Boot Backend Development Course, Implementing Login and Logout with JWT, Prerequisites Token-based Authentication

In this course, we will delve deeply into how to implement login and logout functionality based on JWT (JSON Web Token) using Spring Boot. This article explains the basic concepts of JWT and how to utilize JWT in Spring Boot. Furthermore, we will start with the necessary prerequisites and development environment setup, aiming to enhance understanding through actual code examples.

1. Prerequisites: Token-Based Authentication

Token-based authentication is a technology that provides a reliable authentication method between a server and a client by converting user authentication information into a token. Unlike traditional session-based authentication, this approach is advantageous for scaling as the backend server does not need to maintain the user’s state. JSON Web Token is a widely used standard in such token-based authentication.

1.1 What is JWT?

JWT is a token that contains information encoded in JSON format, primarily used for user authentication and information transmission procedures. JWT is divided into three parts:

  1. Header: Specifies the type of token and the hashing algorithm.
  2. Payload: Contains user information and additional claims (e.g., expiration time).
  3. Signature: Generated by combining the Header and Payload and hashing them with a secret key.

An example of a JWT is as follows:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

1.2 Advantages of JWT

  • Statelessness: The server does not need to maintain sessions.
  • Cross-Domain Authentication: Authentication information can be stored on the client, making it usable across various clients.
  • Security: Capable of encryption and signing on its own.

2. Environment Setup

To use Spring Boot, prepare the following items.

2.1 Development Tool Setup

  1. Install Java Development Kit (JDK) version 17 or higher.
  2. Create a project using Spring Initializr (adding web, security, JPA, and Lombok dependencies).
  3. Install an IDE (IntelliJ IDEA or Eclipse).

2.2 Project Structure

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── jwt
│   │               ├── JwtApplication.java
│   │               ├── controller
│   │               │   └── AuthController.java
│   │               ├── dto
│   │               │   └── AuthRequest.java
│   │               ├── security
│   │               │   ├── JwtRequestFilter.java
│   │               │   └── JwtUtil.java
│   │               └── service
│   │                   └── UserService.java
│   └── resources
│       └── application.properties
└── test

Spring Boot Backend Development Course, Implementing Login and Logout with JWT, Implementing a JWT Service

Implementing Login/Logout with JWT

Table of Contents

  1. Introduction
  2. Introduction to Spring Boot
  3. What is JWT?
  4. Project Setup
  5. Implementing Registration Feature
  6. Implementing Login Feature
  7. Authentication and Authorization using JWT
  8. Creating and Validating JWT Tokens
  9. Implementing Logout Feature
  10. Conclusion

Introduction

Recently, authentication and authorization have become very important issues in web applications. Especially when developing RESTful APIs, there are many considerations in handling user authentication because multiple clients need to be supported. Today, we will explore how to implement a login and logout system based on JWT (JSON Web Token) using Spring Boot.

Introduction to Spring Boot

Spring Boot is a project created to simplify application initialization and configuration in the Spring framework, which is a Java-based web application framework. Spring Boot automatically manages the necessary configurations and dependencies, allowing developers to focus on business logic.

Spring Boot offers several advantages:

  • Allows for quick prototype development.
  • Basic configurations are automatically handled.
  • Includes an embedded Tomcat server, eliminating the need for separate server configuration.

What is JWT?

JWT (JSON Web Token) is a compact and independent standard for securely transmitting information using JSON format. JWT is widely used to handle user authentication and authorization in web applications. The features of JWT include:

  • Self-contained reliability: The transmitted data is signed and can be verified.
  • Simple structure for easy parsing.
  • Can be transmitted via HTTP headers, providing good compatibility with various clients.

JWT consists of three components:

  • Header: Contains token type and signing algorithm information.
  • Payload: Contains user information and claims.
  • Signature: Ensures the integrity of the data by signing based on the header and payload.

Project Setup

To create a Spring Boot project, we use Spring Initializr. Select the necessary dependencies such as Web, JPA, Spring Security, Lombok, and JWT library.


        com.example
        jwt-demo
        0.0.1-SNAPSHOT
        jar

        
            
                org.springframework.boot
                spring-boot-starter-web
            
            
                org.springframework.boot
                spring-boot-starter-data-jpa
            
            
                org.springframework.boot
                spring-boot-starter-security
            
            
                io.jsonwebtoken
                jjwt
                0.9.1
            
            
                org.projectlombok
                lombok
                1.18.12
                provided
            
            
                com.h2database
                h2
                runtime
            
        
        

After adding the above dependencies to the build.gradle file, set up the Spring Boot application. Write database connection and JPA settings in the application.properties file.

Implementing Registration Feature

The registration feature essentially allows the user’s provided information to be stored in the database. A JPA entity class is created to save user information.


        import lombok.AllArgsConstructor;
        import lombok.Getter;
        import lombok.NoArgsConstructor;
        import lombok.Setter;

        import javax.persistence.*;

        @Entity
        @Table(name = "users")
        @Getter @Setter @NoArgsConstructor @AllArgsConstructor
        public class User {
            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
            private Long id;

            @Column(unique = true, nullable = false)
            private String username;

            @Column(nullable = false)
            private String password;

            private String role;
        }
        

Create a repository interface to handle the user information provided during registration.


        import org.springframework.data.jpa.repository.JpaRepository;

        public interface UserRepository extends JpaRepository {
            User findByUsername(String username);
        }
        

Create a service class to handle the registration requests.


        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.security.crypto.password.PasswordEncoder;
        import org.springframework.stereotype.Service;

        @Service
        public class UserService {
            @Autowired
            private UserRepository userRepository;

            @Autowired
            private PasswordEncoder passwordEncoder;

            public void registerUser(User user) {
                user.setPassword(passwordEncoder.encode(user.getPassword()));
                user.setRole("ROLE_USER");
                userRepository.save(user);
            }
        }
        

Implementing Login Feature

The login feature is the process where a user provides authentication information to receive a JWT token from the server. To achieve this, we write a filter class that handles authentication.


        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.security.authentication.AuthenticationManager;
        import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
        import org.springframework.security.core.Authentication;
        import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

        public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
            @Autowired
            private AuthenticationManager authenticationManager;

            @Autowired
            private JwtTokenProvider jwtTokenProvider;

            @Override
            public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                return authenticationManager.authenticate(authRequest);
            }

            @Override
            protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
                String token = jwtTokenProvider.createToken(authResult.getName());
                response.addHeader("Authorization", "Bearer " + token);
                response.getWriter().write("Login Successful");
            }
        }
        

Authentication and Authorization using JWT

This section implements the method to authenticate users when calling an API using JWT. We will create a filter that blocks requests if the JWT token is missing or invalid.


        import org.springframework.security.core.Authentication;
        import org.springframework.security.core.context.SecurityContextHolder;
        import org.springframework.stereotype.Component;
        import org.springframework.web.filter.GenericFilterBean;

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

        @Component
        public class JwtAuthenticationFilter extends GenericFilterBean {
            @Autowired
            private JwtTokenProvider jwtTokenProvider;

            @Override
            public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
                String token = request.getHeader("Authorization");

                if (token != null && jwtTokenProvider.validateToken(token)) {
                    Authentication authentication = jwtTokenProvider.getAuthentication(token);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }

                chain.doFilter(request, response);
            }
        }
        

Creating and Validating JWT Tokens

Create a utility class for generating and validating JWT tokens. This class will include various methods for handling JWT.


        import io.jsonwebtoken.Claims;
        import io.jsonwebtoken.JwtBuilder;
        import io.jsonwebtoken.JwtParser;
        import io.jsonwebtoken.Jwts;
        import io.jsonwebtoken.SignatureAlgorithm;
        import org.springframework.stereotype.Component;

        import java.util.Date;
        import java.util.HashMap;
        import java.util.Map;

        @Component
        public class JwtTokenProvider {
            private final String SECRET_KEY = "mySecretKey";

            public String createToken(String username) {
                Map claims = new HashMap<>();
                return Jwts.builder()
                        .setClaims(claims)
                        .setSubject(username)
                        .setIssuedAt(new Date())
                        .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 10 hours
                        .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                        .compact();
            }

            public boolean validateToken(String token) {
                try {
                    Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
                    return true;
                } catch (Exception e) {
                    return false;
                }
            }
            
            public Authentication getAuthentication(String token) {
                // Implement user authentication logic
            }
        }
        

Implementing Logout Feature

The logout feature allows the user to terminate authentication, which is usually implemented by deleting the JWT token from the client. Furthermore, if the server needs to invalidate the token, a blacklist must be managed.


        import org.springframework.web.bind.annotation.*;

        @RestController
        @RequestMapping("/auth")
        public class AuthController {
            @PostMapping("/logout")
            public ResponseEntity logout(HttpServletRequest request) {
                String token = request.getHeader("Authorization");
                // Logic for registering the token in the blacklist
                return ResponseEntity.ok("Logout Successful");
            }
        }
        

Conclusion

In this tutorial, we explored how to implement login/logout features based on JWT using Spring Boot. JWT is a useful tool for handling authentication and authorization in web services, and it will be a great help in future application development. Additionally, researching more about security and session management can help ensure better security.

If you want to expand your knowledge related to authentication and authorization with JWT, it is recommended to study security best practices along with protocols like OAuth2 and OpenID Connect.