Make WS work with Auth

This commit is contained in:
aditya.chandel
2025-02-16 00:32:50 -07:00
parent d3627a2d3f
commit 4354a43af7
24 changed files with 243 additions and 89 deletions
@@ -1,15 +1,25 @@
package com.adityachandel.booklore.config;
import com.adityachandel.booklore.config.security.WebSocketAuthInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Slf4j
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
private final WebSocketAuthInterceptor webSocketAuthInterceptor;
public WebSocketConfig(WebSocketAuthInterceptor webSocketAuthInterceptor) {
this.webSocketAuthInterceptor = webSocketAuthInterceptor;
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
@@ -19,6 +29,11 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*");
System.out.println("WebSocket endpoint registered at /ws");
log.info("WebSocket endpoint registered at /ws");
}
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(webSocketAuthInterceptor);
}
}
@@ -28,8 +28,12 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final UserRepository userRepository;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
protected boolean shouldNotFilter(HttpServletRequest request) {
return "websocket".equalsIgnoreCase(request.getHeader("Upgrade"));
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String token = getJwtFromRequest(request);
@@ -34,6 +34,7 @@ public class SecurityConfig {
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/v1/auth/register", "/api/v1/auth/login").permitAll()
.requestMatchers("/ws/**").permitAll()
.anyRequest().authenticated()
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
@@ -0,0 +1,65 @@
package com.adityachandel.booklore.config.security;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
@AllArgsConstructor
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
public class WebSocketAuthInterceptor implements ChannelInterceptor {
private final JwtUtils jwtUtils;
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (accessor != null && StompCommand.CONNECT.equals(accessor.getCommand())) {
List<String> authHeaders = accessor.getNativeHeader("Authorization");
if (authHeaders == null || authHeaders.isEmpty()) {
log.warn("WebSocket connection rejected: No Authorization header");
throw new IllegalArgumentException("Missing Authorization header");
}
String token = authHeaders.get(0).replace("Bearer ", "");
Authentication auth = authenticateToken(token);
if (auth == null) {
log.warn("WebSocket connection rejected: Invalid token");
throw new IllegalArgumentException("Invalid Authorization token");
}
accessor.setUser(auth);
log.info("WebSocket authentication successful for user: {}", auth.getName());
}
return message;
}
private Authentication authenticateToken(String token) {
if (!jwtUtils.validateToken(token)) {
return null;
}
String username = jwtUtils.extractUsername(token);
List<SimpleGrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
return new UsernamePasswordAuthenticationToken(username, null, authorities);
}
}