Authenticating WebSocket Connections with JWT in Spring Boot
In modern web applications, WebSocket provides a seamless, bidirectional communication channel that enhances user experiences, especially for real-time applications. But with this power comes responsibility: ensuring secure communication is param...

I am Tuanh.net. As of 2024, I have accumulated 8 years of experience in backend programming. I am delighted to connect and share my knowledge with everyone.
1. Understanding the Basics of WebSocket Authentication
1.1 What is WebSocket?
1.2 Why Use JWT for WebSocket Authentication?
- Compact: JWT tokens are small and easy to transmit.
- Secure: Supports claims that are cryptographically signed.
- Stateless: No need to store session data on the server.
1.3 Challenges in WebSocket Authentication
2. Configuring WebSocket Authentication with JWT in Spring Boot
2.1 Setting Up the WebSocket Endpoint
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOrigins("*")
.withSockJS();
}
}
2.2 Adding JWT Authentication During the WebSocket Handshake
@Component
public class JwtHandshakeInterceptor implements HandshakeInterceptor {
private final JwtTokenProvider jwtTokenProvider;
public JwtHandshakeInterceptor(JwtTokenProvider jwtTokenProvider) {
this.jwtTokenProvider = jwtTokenProvider;
}
@Override
public boolean beforeHandshake(
ServerHttpRequest request,
ServerHttpResponse response,
WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
String token = servletRequest.getServletRequest().getParameter("token");
if (token != null && jwtTokenProvider.validateToken(token)) {
// Add user details to attributes for later use
attributes.put("user", jwtTokenProvider.getUserFromToken(token));
return true;
}
}
return false; // Reject the handshake if token is invalid
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
// No-op
}
}
- The beforeHandshake method extracts the JWT token from the request.
- The token is validated using a JwtTokenProvider.
- If valid, user details are added to the attributes map.
2.3 Creating the JWT Token Provider
@Component
public class JwtTokenProvider {
private final String secretKey = "your-secret-key";
public String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 3600000)) // 1 hour validity
.signWith(SignatureAlgorithm.HS512, secretKey)
.compact();
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
return true;
} catch (JwtException | IllegalArgumentException e) {
return false;
}
}
public String getUserFromToken(String token) {
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody()
.getSubject();
}
}
2.4 Integrating the Interceptor with WebSocket Configuration
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.addInterceptors(new JwtHandshakeInterceptor(jwtTokenProvider))
.setAllowedOrigins("*")
.withSockJS();
}
3. Enhancing Security and Troubleshooting
3.1 Handling Expired Tokens
@PostMapping("/auth/refresh")
public ResponseEntity<String> refreshToken(@RequestParam String token) {
if (jwtTokenProvider.validateToken(token)) {
String username = jwtTokenProvider.getUserFromToken(token);
String newToken = jwtTokenProvider.generateToken(username);
return ResponseEntity.ok(newToken);
}
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
3.2 Logging and Error Handling
4. Conclusion
Read more at : Authenticating WebSocket Connections with JWT in Spring Boot





