Sitemap
Rashi

Rashi

Press enter or click to view image in full size
Spring Boot JWT Authentication: Secure Your REST APIs (Complete Guide)

Spring Boot JWT Authentication: Secure Your REST APIs (Complete Guide)

3 min readMar 7, 2026

--

Security is one of the most important parts of modern applications.

If you build APIs without authentication, anyone can access your data. That’s why most applications use JWT authentication.

JWT is widely used in:

  • Banking apps
  • SaaS platforms
  • Mobile applications
  • Microservices architecture

In this guide you will learn:

  • What JWT is
  • How authentication works
  • How to implement JWT in Spring Boot
  • How to secure REST APIs

By the end, you will have a fully secure Spring Boot API.

What is JWT?

JWT stands for JSON Web Token.

It is a secure token used for authentication between client and server.

Instead of sending username and password in every request, the server sends a token after login.

The client then sends this token with every request.

Example token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

How JWT Authentication Works

The process looks like this:

1️⃣ User logs in with username & password

2️⃣ Server verifies credentials

3️⃣ Server generates a JWT token

4️⃣ Client stores the token

5️⃣ Client sends token with every request

6️⃣ Server validates token before returning data

This makes APIs secure and stateless.

Step 1: Add Dependencies

Add these dependencies in pom.xml.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>

Step 2: Create User Entity

Create a User model.

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

This represents the user table.

Step 3: Create User Repository

Repository allows us to access user data.

public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
}

Step 4: Create JWT Utility Class

This class generates and validates tokens.

@Component
public class JwtUtil {
private String SECRET_KEY = "secret";
public String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}
}

Step 5: Create Authentication Controller

This controller handles login requests.

@RestController
@RequestMapping("/auth")
public class AuthController {
@Autowired
private JwtUtil jwtUtil;
@PostMapping("/login")
public String login(@RequestBody User user) {
// validate user credentials
return jwtUtil.generateToken(user.getUsername());
}
}

When login is successful, the server returns a JWT token.

Step 6: Secure API Endpoints

Now we protect APIs using Spring Security configuration.

Get Rashi’s stories in your inbox

Join Medium for free to get updates from this writer.

Example:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/**").permitAll()
.anyRequest().authenticated());
return http.build();
}
}

Now:

  • /auth/login → public
  • All other APIs → require authentication

Example API Request With Token

Client sends the token in the header.

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Spring Security verifies the token before allowing access.

Benefits of JWT Authentication

JWT has many advantages:

Stateless Authentication

Server does not store session data.

High Performance

JWT reduces database queries.

Secure Communication

Tokens are digitally signed.

Scalable

Perfect for microservices architecture.

Real Applications Using JWT

JWT is widely used in:

  • Web applications
  • Mobile apps
  • REST APIs
  • Microservices

Popular companies use token-based authentication in their systems.

Common Mistakes Beginners Make

Many developers make these mistakes:

❌ Storing passwords in plain text
❌ Not setting token expiration
❌ Exposing secret keys
❌ Not validating tokens properly

Always follow security best practices.

Final Thoughts

JWT authentication is one of the most important backend skills.

In this guide you learned:

  • What JWT is
  • How authentication works
  • How to generate tokens
  • How to secure APIs

With Spring Boot and JWT, you can build secure production-ready applications.

--

--