因此,對於任何人面臨着類似的問題,我實現了我自己主要的類:
package hello;
import java.security.Principal;
import java.util.Objects;
public class AnonymousPrincipal implements Principal {
private String name;
@Override
public String getName() {
// TODO Auto-generated method stub
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object another) {
if (!(another instanceof Principal))
return false;
Principal principal = (Principal) another;
return principal.getName() == this.name;
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
然後,我實現了我自己DefaultHandshakeHandler的版本:
package hello;
import java.security.Principal;
import java.util.Map;
import java.util.UUID;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
public class CustomHandshakeHandler extends DefaultHandshakeHandler {
@Override
protected Principal determineUser(ServerHttpRequest request,
WebSocketHandler wsHandler, Map<String, Object> attributes) {
Principal principal = request.getPrincipal();
if (principal == null) {
principal = new AnonymousPrincipal();
String uniqueName = UUID.randomUUID().toString();
((AnonymousPrincipal) principal).setName(uniqueName);
}
return principal;
}
}
現在的WebSocket會話得到這個在Handshake發生時分配給它的主體,因此如果用戶是匿名的,他們將獲得一個匿名主體,這個主體將允許我存儲他們的名字(生成的UUID),以便以後在應用程序的其他部分使用。