Video tayyorlanmoqda

Spring STOMP'da JWT tokenni CONNECT frame'ida qanday tekshirasiz va foydalanuvchini sessiyaga bog'laysiz?

clientInboundChannel'ga ChannelInterceptor qo'shiladi: CONNECT buyrug'ida header'dan token olinadi, tekshiriladi va accessor.setUser(authentication) qilinadi. Shundan keyin shu sessiyadagi barcha xabarlarda Principal bo'ladi.

📖 Javob

@Configuration
@EnableWebSocketMessageBroker
public class StompAuthConfig implements WebSocketMessageBrokerConfigurer {

    private final JwtDecoder jwtDecoder;
    private final JwtAuthenticationConverter converter = new JwtAuthenticationConverter();

    public StompAuthConfig(JwtDecoder jwtDecoder) { this.jwtDecoder = jwtDecoder; }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor acc =
                    MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                if (acc != null && StompCommand.CONNECT.equals(acc.getCommand())) {
                    String header = acc.getFirstNativeHeader("Authorization");
                    if (header == null || !header.startsWith("Bearer ")) {
                        throw new MessagingException("token yo'q");
                    }
                    Jwt jwt = jwtDecoder.decode(header.substring(7));
                    acc.setUser(converter.convert(jwt));
                }
                return message;
            }
        });
    }
}

Muhim joylari:

  • getAccessor(message, ...) bilan olingan accessor mutable bo'ladi, setUser aynan shu xabarga yoziladi. StompHeaderAccessor.wrap(message) bilan yangi accessor yaratsangiz, o'zgarish yo'qoladi — klassik xato.
  • Exception tashlansa, client ERROR frame oladi va ulanish yopiladi.
  • Spring Security bilan ishlatsangiz, bu interceptor xavfsizlik interceptor'laridan oldin turishi kerak — tartib uchun @Order(Ordered.HIGHEST_PRECEDENCE + 99) beriladigan alohida konfiguratsiya klassi qilinadi.

Keyin destination darajasida ruxsatlarni @EnableWebSocketSecurity va AuthorizationManager<Message<?>> orqali berasiz: masalan, /app/admin.** faqat ADMIN uchun.