Init
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
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<String, Object> 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<String> user = tokenService.resolveUsername(token);
|
||||
return user.<Principal>map(name -> () -> name)
|
||||
.orElseGet(() -> (()-> "anon-" + UUID.randomUUID()));
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user