package de.w665.testing.config; import de.w665.testing.service.TokenService; import org.springframework.http.server.ServerHttpRequest; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; import java.security.Principal; import java.util.Map; import java.util.Optional; import java.util.UUID; public class UsernamePrincipalHandshakeHandler extends DefaultHandshakeHandler { private final TokenService tokenService; public UsernamePrincipalHandshakeHandler(TokenService tokenService) { this.tokenService = tokenService; } @Override protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map attributes) { Object tokenObj = attributes.get("token"); String token = tokenObj != null ? tokenObj.toString() : null; if (token == null) { // Anonymous session (reject by generating random, effectively not mapped to any user) return () -> "anon-" + UUID.randomUUID(); } Optional user = tokenService.resolveUsername(token); return user.map(name -> () -> name) .orElseGet(() -> (()-> "anon-" + UUID.randomUUID())); } }