问题
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
}
}
回答1:
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());
}
来源:https://stackoverflow.com/questions/41285171/websocket-authentication-in-spring-boot