Spring security Spring启动测试在使用@WithMockUser时未验证websocket
我正在尝试使用Spring引导测试来测试websocket连接 当我使用permit all安全配置时,它们工作正常,但一旦我向websocket AbstractSecurityWebSocketMessageBrokerConfigure添加Spring security Spring启动测试在使用@WithMockUser时未验证websocket,spring-security,websocket,spring-websocket,spring-boot-test,Spring Security,Websocket,Spring Websocket,Spring Boot Test,我正在尝试使用Spring引导测试来测试websocket连接 当我使用permit all安全配置时,它们工作正常,但一旦我向websocket AbstractSecurityWebSocketMessageBrokerConfigure添加.nullDestMatcher().authenticated(),测试就会失败,原因是: “消息”:“未能在会话中通过MessageChannel向应用程序发送客户端消息。正在向客户端发送STOMP错误。”,“堆栈跟踪”:“org.springfra
.nullDestMatcher().authenticated()
,测试就会失败,原因是:
“消息”:“未能在会话中通过MessageChannel向应用程序发送客户端消息。正在向客户端发送STOMP错误。”,“堆栈跟踪”:“org.springframework.security.access.AccessDeniedException:访问被拒绝。”
我希望使用@WithMockUser(authorities=AuthoritiesConstants.ADMIN)
会为套接字留下经过身份验证的上下文。我做错了什么
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@WithMockUser(authorities = AuthoritiesConstants.ADMIN)
public class SocketIT {
...
@BeforeEach
public void setup() throws Exception {
blockingQueue = new LinkedBlockingDeque<>();
List<Transport> transports = new ArrayList<>();
transports.add(new WebSocketTransport(new StandardWebSocketClient()));
this.sockJsClient = new SockJsClient(transports);
this.stompClient = new WebSocketStompClient(sockJsClient);
this.stompClient.setMessageConverter(new MappingJackson2MessageConverter());
}
@Test
public void shouldReceiveAMessageFromTheServer() throws Exception {
StompSession session = stompClient
.connect(getWsPath(), new StompSessionHandlerAdapter() {})
.get(1, SECONDS);
}
private String getWsPath() {
return String.format("ws://localhost:%d/websocket/tracker", port);
}
您可以添加Spring安全配置或WebSocket endpointsHi@rieckpil的相关部分吗?我已经在上面进行了编辑,以包含更多相关代码。我认为套接字升级之前的http请求没有经过MockMvc,因此Spring引导测试无法注入主体。我在web上找不到任何测试来测试身份验证作为集成测试,我开始觉得尝试它很奇怪:)你能添加Spring安全配置或WebSocket endpointsHi@rieckpil的相关部分吗,我在上面编辑了包含更多相关代码。我认为套接字升级之前的http请求不经过MockMvc,所以Spring引导测试无法插入我在网上找不到任何测试来测试集成测试中的身份验证,我开始觉得尝试它很奇怪:)
@Configuration
public class WebsocketSecurityConfiguration extends AbstractSecurityWebSocketMessageBrokerConfigurer {
@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
//.nullDestMatcher().authenticated()
.anyMessage().permitAll();
}
@Override
protected boolean sameOriginDisabled() {
return true;
}
}
@Configuration
@EnableWebSocketMessageBroker
public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer {
public static final String IP_ADDRESS = "IP_ADDRESS";
private final JHipsterProperties jHipsterProperties;
public WebsocketConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
String[] allowedOrigins = Optional.ofNullable(jHipsterProperties.getCors().getAllowedOrigins()).map(origins -> origins.toArray(new String[0])).orElse(new String[0]);
registry.addEndpoint("/websocket/tracker")
.setHandshakeHandler(defaultHandshakeHandler())
.setAllowedOrigins(allowedOrigins)
.withSockJS()
.setInterceptors(httpSessionHandshakeInterceptor());
}
@Bean
public HandshakeInterceptor httpSessionHandshakeInterceptor() {
return new HandshakeInterceptor() {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
attributes.put(IP_ADDRESS, servletRequest.getRemoteAddress());
}
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
}
};
}
private DefaultHandshakeHandler defaultHandshakeHandler() {
return new DefaultHandshakeHandler() {
@Override
protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
Principal principal = request.getPrincipal();
if (principal == null) {
Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
principal = new AnonymousAuthenticationToken("WebsocketConfiguration", "anonymous", authorities);
}
return principal;
}
};
}
}
@MessageMapping("/topic/activity")
@SendTo("/topic/tracker")
public ActivityDTO sendActivity(@Payload ActivityDTO activityDTO, StompHeaderAccessor stompHeaderAccessor, Principal principal) {
activityDTO.setUserLogin(principal.getName());
activityDTO.setSessionId(stompHeaderAccessor.getSessionId());
activityDTO.setIpAddress(stompHeaderAccessor.getSessionAttributes().get(IP_ADDRESS).toString());
activityDTO.setTime(Instant.now());
log.debug("Sending user tracking data {}", activityDTO);
return activityDTO;
}