In this lecture we'll:
- Set up Spring Security to protect your application.
- Integrate and configure JWT for authentication.
- Implement token validation and access rules for the API.
- Learn how to generate and validate JWT tokens.
Setting up Spring Security
Spring Security is like a Swiss Army knife for securing applications. It supports everything from authentication and authorization to advanced encryption mechanisms. Let's start with a basic config and then add JWT.
Adding the dependency
If you're using Maven, add this dependency to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
If you're on Gradle:
implementation 'org.springframework.boot:spring-boot-starter-security'
Creating the basic configuration class
Let's create a configuration class for Spring Security:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable() // Disable CSRF for REST API
.authorizeRequests()
.antMatchers("/api/auth/**").permitAll() // Allow access to auth API
.anyRequest().authenticated() // All other requests require authentication
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // JWT = stateless
}
}
JSON Web Token (JWT): what it is and why it matters
JWT is a standard used to transmit data between client and server in a compact, URL-safe format. Think of it like a locked safe with a password: whoever has the key (the secret) can "open" it and read the contents.
Each JWT has three parts:
- Header (information about the token type and signing algorithm) — contains the token type and algorithm info.
- Payload (the claims) — this is where user data is stored (ID, roles).
- Signature (the signature) — used to verify the token's authenticity.
Generating JWT tokens
We're going to use the jjwt library. Add it to your pom.xml:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
Now let's create a utility class to work with tokens.
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class JwtTokenUtil {
private final String SECRET_KEY = "secret"; // Use a stronger key in real projects!
public String generateToken(String username) {
return Jwts.builder()
.setSubject(username) // Set the user
.setIssuedAt(new Date()) // Token issue date
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // Token expires in 10 hours
.signWith(SignatureAlgorithm.HS256, SECRET_KEY) // Signing algorithm
.compact();
}
public String extractUsername(String token) {
return Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody()
.getSubject();
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
return true;
} catch (JwtException | IllegalArgumentException e) {
return false; // Token is invalid
}
}
}
Adding a filter to validate tokens
Now let's write a filter that will run on each request and check the JWT's validity.
Implementing authentication endpoints
Now let's create a controller that will generate JWT tokens:
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private final JwtTokenUtil jwtTokenUtil;
public AuthController(JwtTokenUtil jwtTokenUtil) {
this.jwtTokenUtil = jwtTokenUtil;
}
@PostMapping("/login")
public ResponseEntity
createAuthenticationToken(@RequestBody AuthRequest authRequest) {
// Here you can add user validation logic (for example, checking a database!)
String token = jwtTokenUtil.generateToken(authRequest.getUsername());
return ResponseEntity.ok(new AuthResponse(token));
}
}
class AuthRequest {
private String username;
private String password;
// getters/setters
}
class AuthResponse {
private final String token;
public AuthResponse(String token) {
this.token = token;
}
public String getToken() {
return token;
}
}
Summary: what we did?
We set up Spring Security, implemented JWT tokens, and added basic protection to your REST API. Now your application is considerably more secure.
GO TO FULL VERSION