|
| 1 | +package com.metarash.backend.interceptor; |
| 2 | + |
| 3 | +import com.metarash.backend.security.jwt.JwtService; |
| 4 | +import lombok.RequiredArgsConstructor; |
| 5 | +import lombok.extern.slf4j.Slf4j; |
| 6 | +import org.springframework.messaging.Message; |
| 7 | +import org.springframework.messaging.MessageChannel; |
| 8 | +import org.springframework.messaging.simp.stomp.StompCommand; |
| 9 | +import org.springframework.messaging.simp.stomp.StompHeaderAccessor; |
| 10 | +import org.springframework.messaging.support.ChannelInterceptor; |
| 11 | +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| 12 | +import org.springframework.security.core.Authentication; |
| 13 | +import org.springframework.stereotype.Component; |
| 14 | + |
| 15 | +@Slf4j |
| 16 | +@Component |
| 17 | +@RequiredArgsConstructor |
| 18 | +public class WebSocketAuthChannelInterceptor implements ChannelInterceptor { |
| 19 | + |
| 20 | + private final JwtService jwtService; |
| 21 | + |
| 22 | + @Override |
| 23 | + public Message<?> preSend(Message<?> message, MessageChannel channel) { |
| 24 | + StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); |
| 25 | + log.info("[WS-INTERCEPTOR] Incoming command: {}", accessor.getCommand()); |
| 26 | + if (StompCommand.CONNECT.equals(accessor.getCommand())) { |
| 27 | + String authHeader = accessor.getFirstNativeHeader("Authorization"); |
| 28 | + log.info("[WS-INTERCEPTOR] Authorization header: {}", authHeader); |
| 29 | + if (authHeader != null && authHeader.startsWith("Bearer ")) { |
| 30 | + String token = authHeader.substring(7); |
| 31 | + log.info("[WS-INTERCEPTOR] Extracted token: {}", token); |
| 32 | + String username = jwtService.getEmailFromToken(token); |
| 33 | + log.info("[WS-INTERCEPTOR] Parsed username/email from token: {}", username); |
| 34 | + boolean valid = jwtService.validateJwtToken(token); |
| 35 | + log.info("[WS-INTERCEPTOR] Token valid: {}", valid); |
| 36 | + if (username != null && valid) { |
| 37 | + Authentication auth = new UsernamePasswordAuthenticationToken(username, null, /* authorities */ null); |
| 38 | + accessor.setUser(auth); |
| 39 | + log.info("[WS-INTERCEPTOR] Principal set: {}", username); |
| 40 | + } else { |
| 41 | + log.info("[WS-INTERCEPTOR] JWT invalid or username not found"); |
| 42 | + } |
| 43 | + } else { |
| 44 | + log.info("[WS-INTERCEPTOR] No valid Authorization header found"); |
| 45 | + } |
| 46 | + } |
| 47 | + return message; |
| 48 | + } |
| 49 | +} |
0 commit comments