Hello! Welcome back.
In our last lesson, we built a secure user registration endpoint. You can now create users whose passwords are safely stored in the database as BCrypt hashes. This was a critical first step in securing our platform.
Today, we'll build the other half of the core authentication puzzle. Our goal is to build a login endpoint that validates credentials and generates JWT access and refresh tokens. We'll authenticate the users you created, and upon success, issue them the "keys" they'll need to access protected parts of our API.
1. Introduction to JWT and the Refresh Token Strategy
In your MERN projects, you've likely used JSON Web Tokens (JWTs) for stateless authentication. Spring Boot applications leverage the same principles. When a user logs in, we don't want the server to have to remember them in a session. Instead, we give the user a signed token they can present with each request to prove who they are.
However, a simple access token has a flaw: if it's long-lived for user convenience, it's a security risk if stolen. If it's short-lived, the user is forced to log in frequently. The solution is the access token + refresh token pattern.
Implement JWT Auth with Refresh Tokens in Spring Security (Full Tutorial)
To understand this pattern, watch the first few minutes of this video from Learn With Ifte. It gives a great overview of the problem with session-based authentication and introduces the access/refresh token strategy.
Watch from the beginning until 03:37. Focus on the distinction between short-lived access tokens and long-lived refresh tokens and why this pattern is essential for modern applications.
Here is a diagram illustrating the full flow, which we will build over this lesson and the next.

MERN Comparison: Filters vs. Middleware
In your Express.js applications, you use a chain of middleware functions to process incoming requests. Spring Security uses an analogous concept called the FilterChain. Each request passes through a series of filters that can inspect, modify, or reject it.

When a user tries to log in, a specific filter, UsernamePasswordAuthenticationFilter, is responsible for handling it. Our job is to configure the central brain of Spring Security, the AuthenticationManager, to correctly process this authentication attempt.
2. Setting Up JWT Dependencies and Configuration
First, we need to add the necessary libraries for creating and managing JWTs to our pom.xml.
Open your pom.xml file and add these dependencies inside the <dependencies> block.
<!-- For JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.12.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.12.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.12.5</version>
<scope>runtime</scope>
</dependency>
After adding these, reload your Maven project in your IDE to download the libraries.
Next, let's add our JWT configuration to src/main/resources/application.yml. This keeps our secrets and settings external from our code.
# Add this section to your application.yml
jwt:
secret: "YOUR_VERY_STRONG_AND_SECRET_KEY_THAT_IS_AT_LEAST_256_BITS_LONG_FOR_HS256"
access-token-expiration: 3600000 # 1 hour in milliseconds
refresh-token-expiration: 604800000 # 7 days in milliseconds
Security Note: For a real production application, this secret key should not be in your version control. It should be injected via environment variables or a secret management service (like AWS Secrets Manager). You can generate a strong key using an online tool or via openssl rand -base64 32 in your terminal.
3. The JwtService: Our Token Factory
We'll create a dedicated service to handle all JWT-related logic: generation, parsing, and validation. This follows the Single Responsibility Principle.
- Create a new class
JwtServicein yourcom.example.blogplatform.servicepackage.
package com.example.blogplatform.service;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Service
public class JwtService {
@Value("${jwt.secret}")
private String jwtSecret;
@Value("${jwt.access-token-expiration}")
private long accessTokenExpiration;
@Value("${jwt.refresh-token-expiration}")
private long refreshTokenExpiration;
public String generateAccessToken(UserDetails userDetails) {
return buildToken(new HashMap<>(), userDetails, accessTokenExpiration);
}
public String generateRefreshToken(UserDetails userDetails) {
return buildToken(new HashMap<>(), userDetails, refreshTokenExpiration);
}
private String buildToken(Map<String, Object> extraClaims, UserDetails userDetails, long expiration) {
return Jwts.builder()
.claims(extraClaims)
.subject(userDetails.getUsername())
.issuedAt(new Date(System.currentTimeMillis()))
.expiration(new Date(System.currentTimeMillis() + expiration))
.signWith(getSignInKey(), Jwts.SIG.HS256)
.compact();
}
private SecretKey getSignInKey() {
byte[] keyBytes = Decoders.BASE64.decode(jwtSecret);
return Keys.hmacShaKeyFor(keyBytes);
}
// We will add more methods here in the next lesson (like extractUsername, isTokenValid)
}
Key Points:
@Value: This annotation injects the properties we just defined inapplication.yml.buildToken: This private method is the core token builder. It sets standard claims like subject (sub), issued-at (iat), and expiration (exp), and then signs the token with our secret key using the HMAC-SHA256 algorithm.getSignInKey: This helper method decodes our Base64 secret key into theSecretKeyobject that thejjwtlibrary requires.
4. Building the Login Endpoint
Now we can assemble the pieces into a working login endpoint.
Step 1: Expose the AuthenticationManager Bean
The AuthenticationManager is the central component in Spring Security that processes an authentication request. We need to expose it as a bean so we can inject it into our AuthService.
In your SecurityConfig.java, add the following bean. You will also need to import AuthenticationConfiguration.
// In SecurityConfig.java
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
// ... inside the SecurityConfig class
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
Step 2: Create DTOs for Request and Response
We need data transfer objects for a clean API contract.
- Create a
LoginDto.javarecord in themodel.dtopackage:package com.example.blogplatform.model.dto; public record LoginDto(String username, String password) { } - Create an
AuthResponseDto.javarecord in the same package:package com.example.blogplatform.model.dto; public record AuthResponseDto(String accessToken, String refreshToken) { }
Step 3: Update the AuthService
Now, let's add the login logic to our AuthService.
Inject AuthenticationManager and JwtService into your AuthService.java. The @RequiredArgsConstructor annotation will handle this for you if you make the fields final.
// In AuthService.java
import com.example.blogplatform.model.dto.LoginDto;
import com.example.blogplatform.model.dto.AuthResponseDto;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
@Service
@RequiredArgsConstructor
public class AuthService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JwtService jwtService; // Add this
private final AuthenticationManager authenticationManager; // Add this
// ... your existing signUp method ...
public AuthResponseDto login(LoginDto loginDto) {
// This line is where Spring Security does its magic ✨
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginDto.username(),
loginDto.password()
)
);
// If authentication is successful, the code proceeds.
// If not, an AuthenticationException is thrown and the method stops.
var user = userRepository.findByUsername(loginDto.username())
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
var accessToken = jwtService.generateAccessToken(user);
var refreshToken = jwtService.generateRefreshToken(user);
return new AuthResponseDto(accessToken, refreshToken);
}
}
The authenticationManager.authenticate() call is the most important part. It triggers the entire Spring Security authentication process:
- It uses the
UserDetailsService(which we configured implicitly by having ourUserimplement it and by creating aUserRepository) to find the user by username. - It uses the
PasswordEncoderbean we created in the last lesson to hash the submitted password and compare it securely to the one in the database. - If they don't match, it throws an exception, resulting in a
401 Unauthorizedresponse.
Step 4: Update the AuthController
Finally, expose the login method via a controller endpoint.
Add the following method to your AuthController.java:
// In AuthController.java
import com.example.blogplatform.model.dto.LoginDto;
import com.example.blogplatform.model.dto.AuthResponseDto;
// ... inside the AuthController class
@PostMapping("/login")
public ResponseEntity<AuthResponseDto> login(@RequestBody LoginDto loginDto) {
AuthResponseDto response = authService.login(loginDto);
return ResponseEntity.ok(response);
}
5. Runtime Observation: Putting It All Together
Let's test our new endpoint.
- Start your Spring Boot application.
- Open Postman and create a
POSTrequest tohttp://localhost:8080/api/auth/login. - In the "Body" tab, select "raw" and "JSON", and use the credentials of the user you created in the last lesson:
{ "username": "testuser", "password": "strongPassword123" } - Send the request. You should get a
200 OKresponse with a JSON body containing youraccessTokenandrefreshToken!
A successful login request in Postman returns a JSON object with the access and refresh tokens.
Now, let's inspect the token.
- Copy the
accessTokenvalue from the response. - Go to the website jwt.io.
- Paste your token into the "Encoded" text area on the left.
- You will see the decoded payload on the right. Notice the
sub(subject, your username),iat(issued at), andexp(expiration) claims. - To verify the signature, scroll down to "Verify Signature". In the secret box, paste the secret key from your
application.yml. The "Signature Verified" message should appear.
Debugging Exercise
- In Postman, change the password in your request body to something incorrect (e.g., "wrongPassword").
- Send the request again.
- Observe the response. You will get a
403 Forbiddenerror. Check the application console logs, and you will see messages from Spring Security indicating "Bad credentials". This confirms our validation is working correctly.
Conclusion
Fantastic work today! You have successfully implemented a production-grade login endpoint. You've now seen how Spring Security's powerful, declarative model handles the complex and error-prone logic of password verification for you.
Key Takeaways:
- The access token + refresh token pattern provides a balance of security and user experience.
- The
AuthenticationManageris the core of Spring Security's authentication process, coordinating theUserDetailsServiceandPasswordEncoder. - A dedicated
JwtServicecleanly encapsulates all token-related operations. - The overall flow is Controller → Service → AuthenticationManager, which, if successful, allows a call to the JwtService to generate tokens.
- Always inspect generated artifacts like JWTs using tools like
jwt.ioto confirm they are being created correctly.
Preview of the Next Lesson:
We can now register a user and get tokens by logging in. But what can we do with these tokens? Right now, nothing. In our next lesson, "Implement a custom security filter to validate JWTs," we will create a custom filter that intercepts every incoming request, validates the access token, and sets the user's security context, finally allowing them to access the protected endpoints we defined earlier.