
September 24, 2025 06:56 by
Peter
Security is a primary concern in contemporary web applications. JWT (JSON Web Token) authentication is a widely used method for securing REST APIs. Without keeping session data on the server, JWT enables your API to safeguard sensitive endpoints and authenticate users.
1. What is JWT?
JWT (JSON Web Token) is a compact token format that contains user information (claims) and is signed digitally.
Structure: JWT has three parts separated by dots:
Example
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMSIsImlhdCI6MTY4MDAwMDAwMCwiZXhwIjoxNjgwMDAzNjAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Purpose: JWT allows stateless authentication where the server does not need to store user sessions.
2. Create a Spring Boot Project
Use Spring Initializr to create a new project.
Add dependencies:
- Spring Web
- Spring Security
- Spring Data JPA (optional, for storing user data)
- jjwt (for JWT token creation)
3. Define User Model and Repository
- Create a User entity representing users in your database.
- Create a UserRepository to handle database operations.
Example
@Entity
public class User {
@Id @GeneratedValue
private Long id;
private String username;
private String password;
private String role;
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
}
4. Configure Spring Security
Create a SecurityConfig class that extends WebSecurityConfigurerAdapter.
Disable the default login form and enable the JWT filter.
Example
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
5. Create JWT Utility Class
- Generate and validate JWT tokens.
- Use io.jsonwebtoken (jjwt) library.
Example
@Component
public class JwtUtil {
private String secret = "mySecretKey";
public String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}
public String extractUsername(String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject();
}
public boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
}
6. Implement Authentication Controller
Create endpoints for login and token generation.
Example
@RestController
@RequestMapping("/auth")
public class AuthController {
@Autowired private AuthenticationManager authenticationManager;
@Autowired private JwtUtil jwtUtil;
@Autowired private UserDetailsService userDetailsService;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody AuthRequest request) {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
final UserDetails userDetails = userDetailsService.loadUserByUsername(request.getUsername());
final String token = jwtUtil.generateToken(userDetails.getUsername());
return ResponseEntity.ok(new AuthResponse(token));
}
}
AuthRequest and AuthResponse are simple POJOs to carry request and response data.
7. Create JWT Filter
Intercepts incoming requests, extracts the JWT token from headers, and validates it.
Example
@Component
public class JwtFilter extends OncePerRequestFilter {
@Autowired private JwtUtil jwtUtil;
@Autowired private UserDetailsService userDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");
String username = null;
String token = null;
if (authHeader != null && authHeader.startsWith("Bearer ")) {
token = authHeader.substring(7);
username = jwtUtil.extractUsername(token);
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (jwtUtil.validateToken(token, userDetails)) {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
chain.doFilter(request, response);
}
}
8. Test Your REST API
Start the Spring Boot application.
Use Postman or curl to test:
/auth/login with username/password → get JWT token.
Access protected endpoints with Authorization: Bearer <token> header.
Example curl command
curl -H "Authorization: Bearer <your_token_here>" http://localhost:8080/api/protected
Bash
If everything is correct, the request succeeds; otherwise, it returns 401 Unauthorized.
Summary
You may create safe, stateless REST APIs with Spring Boot's JWT authentication. You may successfully secure your API by following these steps: building a user model, setting up Spring Security, producing JWT tokens, putting filters in place, and testing your endpoints. Because JWT is scalable, safe, and lightweight, it is frequently employed in contemporary online and mobile apps.
European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.
