Reputation: 1
I am building a chat in my spring boot application using web sockets, and it is my first time using web sockets. I am using JWT authentication in my app, and I have configured the Web Socket like this:
@Configuration
@EnableWebSocketMessageBroker
@RequiredArgsConstructor
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
private final JwtService jwtService;
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOrigins("*")
.setHandshakeHandler(new CustomHandshakeHandler(jwtService))
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/user");
registry.setApplicationDestinationPrefixes("/app");
registry.setUserDestinationPrefix("/user");
}
@Override
public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
DefaultContentTypeResolver resolver = new DefaultContentTypeResolver();
resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON);
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setObjectMapper(new ObjectMapper());
converter.setContentTypeResolver(resolver);
messageConverters.add(converter);
return false;
}
}`
I want the users that will use the chat to be authenticated, so in spring security configuration I added
.requestMatchers("/ws/**").authenticated()
I have implemented a custom handshake handler that is like this:
@RequiredArgsConstructor
public class CustomHandshakeHandler implements HandshakeHandler {
private final JwtService jwtService;
@Override
public boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
String token = request.getHeaders().getFirst("Authorization");
if (token != null && token.startsWith("Bearer ")) {
token = token.substring(7);
if (jwtService.isTokenValid(token, jwtService.getUserDetails(token))) {
Authentication auth = jwtService.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(auth);
return true;
}
}
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return false;
}
}
When I tried to test it from postman at url: ws://localhost:8080/ws
Error: Unexpected server response: 400
Handshake Details
Request Method: GET
Status Code: 400
Request Headers
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: zdCqDiMyLH7SuDAEAg/5MQ==
Connection: Upgrade
Upgrade: websocket
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhbGV4bGVub25AZ21haWwuY29tIiwiaWF0IjoxNzI0NTMzOTE1LCJleHAiOjE3MjQ1NDExMTV9.4pir4RxyeGshCYPFAY43TCjrZJI8B5iRKjSg-MvS8LY
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: localhost:8080
Response Headers
Vary
0: Origin
1: Access-Control-Request-Method
2: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
X-Frame-Options: DENY
Content-Security-Policy: connect-src 'self' ws://localhost:8080
Content-Length: 0
Date: Sat, 24 Aug 2024 21:12:30 GMT
Connection: close
Online
As I said it's my first time using web socket and I can't understand where the problem comes from, if someone can help me I would be thankful
Upvotes: 0
Views: 59