我有一个具有身份验证/授权功能的工作 Spring Boot 服务器。当尝试打开与 SockJS 的连接时,它被我的其他安全措施阻止。
我还不完全理解 Java 中的安全流程是如何工作的,但我很想在尝试与 SockJS 连接时需要通过握手传递 JWT token 。据我了解,SockJS 不可能做到这一点。所以我只是想知道使用 JWT 启动套接字的最佳方法是什么。另外,我知道我没有启用 CSRF,所以一些关于这方面的提示也很好。
在 WebSecurityConfig.java 中:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors();
httpSecurity.csrf().disable()
.authorizeRequests()
.antMatchers("/authenticate", "/login", "/register").permitAll()
.anyRequest().authenticated().and()
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
在 WebSocketConfig.java 中:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOrigins("http://localhost:5000")
.withSockJS();
}
}
在我的 Vue 应用程序中。尝试使用 JS 连接:
connect() {
this.socket = new SockJS("http://localhost:8080/ws");
this.stompClient = Stomp.over(this.socket);
this.stompClient.connect(
{
token: 'Bearer ' + localStorage.getItem('user-token')
},
frame => {
this.connected = true;
console.log(frame);
this.stompClient.subscribe("/topic/greetings", tick => {
console.log(tick);
this.received_messages.push(JSON.parse(tick.body).content);
});
},
error => {
console.log(error);
this.connected = false;
})
},
如果我删除所有安全配置,我就可以很好地连接到 WebSocket。
我希望能够连接到 WebSocket,但现在我收到 401,并且在握手时找不到进行身份验证的方法。
最佳答案
自营
我通过在 WebSecurityConfig.java
中禁用握手路径的安全性来解决这个问题,如下所示
.antMatchers(
"/authenticate",
"/login",
"/register",
"/secured/chat/**").permitAll()
我想我现在必须通过套接字对用户进行身份验证,因为这会使套接字向任何人开放,这是我真正不想要的。
关于java - 尝试建立 WebSocket 连接时 JWT 身份验证阻止 SockJS 握手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58489490/