I am building a small websocket project and secured by JWT token mechanism and I would like to store websocket sessions in redis not local memory.
@Override
protected void configureStompEndpoints(StompEndpointRegistry registry) {
registry
.addEndpoint("/hello")
.addInterceptors(new HttpSessionHandshakeInterceptor() {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession();
attributes.put("sessionId", session.getId());
}
return true;
}
})
.withSockJS()
.setSessionCookieNeeded(true);
}
I @EnableRedisHttpSession in my redis config and the source code above safely stores http session in redis but even though I flushed my redis database, I can still send and receive my messages to my connected clients.
My speculation is that HttpSession is different from WebSocket session. How should I "intelligently" ask spring to store and maintain websocket related sessions in redis if you are using token based authentication?
UPDATE 1
StompHeaderAccessor accessor =
MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
List<String> tokenList = accessor.getNativeHeader("username");
accessor.removeHeader("username");
String username = null;
if (tokenList != null && tokenList.size() > 0) {
username = tokenList.get(0);
}
AuthenticationToken authToken = new AuthenticationToken(username);
SecurityContextHolder.getContext().setAuthentication(authToken);
switch(accessor.getCommand()) {
case CONNECT:
Principal auth = username == null ? null : authToken;
accessor.setUser(auth);
return MessageBuilder.createMessage(message.getPayload(), accessor.getMessageHeaders());
case CONNECTED:
System.out.println("Stomp connected");
break;
case DISCONNECT:
System.out.println("Stomp disconnected");
break;
case SEND:
break;
default:
break;
}
return message;
UPDATE 2
I think Websocket over STOMP relies on SimpSessionId not HttpSession created during the Handshake Interceptor.
StompHeaderAccessor [headers={simpMessageType=MESSAGE, stompCommand=SEND, nativeHeaders={username=[*******], destination=[/app/feed], content-length=[81]}, simpSessionAttributes={SPRING.SESSION.ID=187912de-a875-45ef-995a-7723fd8715c8}, simpHeartbeat=[J@6e9173e4, simpUser=***.AuthenticationToken@1767840c: Principal: *******; Credentials: [PROTECTED]; Authenticated: true; Details: null; Not granted any authorities, simpSessionId=d686qam8, simpDestination=/app/feed}]
UPDATE 3
SimpUserRegistry says this is "A registry of currently connected users." Might be this is the answer?
UPDATE 4
I am using RabbitMQ. Does that mean what I am doing is completely useless?