WebSocket, authentication in Spring Boot

久未见 提交于 2019-12-12 01:27:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!