Implementing JWT Authentication in a Spring Boot Application

The Code Bean
3 min readSep 19, 2023

--

JWT Authentication + Spring Boot
JWT Authentication + Spring Boot | The Code Bean

JSON Web Tokens (JWT) have become a popular method for securing modern web applications. JWTs allow you to transmit information securely between parties as a compact, self-contained, and digitally signed JSON object. In this blog post, we will walk you through the steps to implement JWT authentication in a Spring Boot application.

Step 1: Create a Spring Boot Project

Set up a new Spring Boot project using your preferred IDE or the Spring Initializr (https://start.spring.io/).

Step 2: Add Dependencies

To get started, you’ll need to add the necessary dependencies to your pom.xml file. In this example, we'll use Spring Security and the jjwt library for JWT support. Here's what your dependencies section should look like:

<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- JWT Library -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version> <!-- Use the latest version available -->
</dependency>
</dependencies>

Step 3: Configure Spring Security

Create a security configuration class that extends WebSecurityConfigurerAdapter. In this class, configure the security settings, including authentication and authorization rules. Additionally, exclude the login and token endpoints from authentication to allow unauthenticated access.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login", "/token").permitAll() // Exclude login and token endpoints from authentication
.anyRequest().authenticated();
}
}

Step 4: Create a UserDetailsService

Implement a custom UserDetailsService to load user details from your chosen data source, such as a database.

Step 5: Create a JWT Utility Class

Develop a utility class for generating and parsing JWTs using the jjwt library. This class will be responsible for creating JWTs when users log in and validating incoming JWTs.

import io.jsonwebtoken.*;
public class JwtUtil {
private static final String SECRET = "your-secret-key";
private static final long EXPIRATION_TIME = 864_000_000; // 10 days
public static String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
}
public static String extractUsername(String token) {
return Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token)
.getBody()
.getSubject();
}
}

Step 6: Create a Login Endpoint

Design an endpoint where users can log in and obtain a JWT. Here’s a simple example using a Spring @RestController:

@RestController
public class AuthController {
@PostMapping("/login")
public String login(@RequestBody LoginRequest request) {
// Authenticate the user (e.g., using Spring Security's authentication manager)
// If authentication is successful, generate a JWT
String token = JwtUtil.generateToken(request.getUsername());
return token;
}
}

Step 7: Create a Protected Resource Endpoint

Develop an endpoint that requires a valid JWT for access. Use Spring Security annotations to enforce authorization based on roles or other criteria.

@RestController
public class ProtectedResourceController {

@GetMapping("/protected")
@Secured("ROLE_USER") // Role-based authorization
public String protectedResource() {
return "This is a protected resource.";
}
}

Step 8: Token Validation and Authentication Filter

Implement a custom filter that intercepts incoming requests, validates the JWT, and sets up the authentication context if the token is valid. You can use Spring Security’s OncePerRequestFilter for this purpose.

Step 9: Test Your Endpoints

You can use tools like Postman or cURL to test your login and protected resource endpoints. Ensure that you include the JWT in the Authorization header when accessing protected resources.

Step 10: Secure Your Secret Key

Store your JWT secret key securely. Consider using a properties file, environment variable, or a secret management tool to protect this sensitive information.

Step 11: Handle Token Expiration and Refresh (Optional)

Depending on your application’s requirements, you may need to implement token expiration and refresh logic.

Step 12: Logging and Error Handling

Ensure that your application includes proper logging and error handling to address security-related issues effectively.

By following these steps, you can successfully implement JWT authentication in your Spring Boot application, enhancing security and protecting your resources. Remember to adapt these instructions to your specific application’s needs and consult with security experts to ensure your application remains secure.

--

--

The Code Bean

Tech enthusiasts community sharing knowledge on coding, software design, and web development. 🚀