In Week 4, we connected our Spring Boot APIs to a real database using JPA and Hibernate.
Now, in Week 5, it’s time to secure your APIs with Spring Security and JWT (JSON Web Token) authentication — the standard for modern web and mobile apps.
By the end of this article, your APIs will be protected, supporting login, registration, and role-based access control.
Why JWT + Spring Security?
Traditional session-based authentication has challenges:
Hard to scale in microservices
Requires server-side session storage
Not mobile/web friendly
JWT solves these problems:
Stateless authentication (no server session)
Works across multiple services
Easy to integrate with mobile and SPA frontends
Step 1: Add Dependencies
In your 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>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>This includes Spring Security + JJWT library for token generation and validation.
Step 2: User Entity & Roles
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String role; // e.g., ROLE_USER, ROLE_ADMIN
// Getters & Setters
}Passwords must be hashed before storing. Never store plaintext passwords.
Step 3: Password Encryption
Use BCryptPasswordEncoder:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}