因此,对于任何人面临着类似的问题,我实现了我自己主要的类:
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),以便以后在应用程序的其他部分使用。