简体   繁体   中英

WebSocket, authentication in Spring Boot

I want make some chat, it already works, but i can't get context from SecurityContextHolder, it's always null. Annotations @PreAuthorize and @Secured don't work too, becouse of nulable SecurityContext. How i can get this context or principal? In ordinary controllers it works, but not with the websocket. I want add to message information about user, maybe there is another way?

My configuration:

@Configuration
@EnableWebSocketMessageBroker
@ComponentScan(basePackages = "com.antilamer.controller")
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("/chat").withSockJS();
    }
}

Controller:

@Controller
public class ChatController {
    @MessageMapping("/chat")
    @SendTo("/topic/message")
    public OutputMessageDTO sendMessage(MessageDTO message) {
        return new OutputMessageDTO(message, new Date()); //here i want use my SecurityContext
    }
}

Ok, we can't use security context with websocket, but I found way to get logged user, I need change my sendMessage() method:

public OutputMessageDTO sendMessage(SimpMessageHeaderAccessor headerAccessor, MessageDTO message) {
    return new OutputMessageDTO(message, new Date(), headerAccessor.getUser());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM