除了他的名字外,我找不到其他用户,但是id或完整用户并不需要唯一的名字 我有
@Component
public class WebSocketEventListener {
private static final Logger logger =
LoggerFactory.getLogger(WebSocketEventListener.class);
@EventListener
public void handleWebSocketConnectListener(SessionConnectedEvent event) {
logger.info("Received a new web socket connection");
System.out.println("User connection : " + event.getUser());
}
}
有一个方法getUser()getName,但名称不是唯一的, 和方法event.getUser()提供了一些可怕的东西))-
User connection :
org.springframework.security.authentication.UsernamePasswordAuthenticationToken@fe260c00: Principal:
User(id=1, username=admin, password=$2a$08$VDogbqVQY23gNnLFty/6ReGLecW/bk3oCkUHrsly4HgjBIGRNBSEC,
email=kiy9@gmail.com); Credentials: [PROTECTED]; Authenticated: true; Details:
org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress:
0:0:0:0:0:0:0:1; SessionId: 3566D00689DCC01041367983F3132937; Granted Authorities: USER
有什么方法可以从那里获得用户或id吗?
如果我尝试User user = event.getUser()或((User)event.getUser())。getId() 我得到
java.lang.ClassCastException:
org.springframework.security.authentication.
UsernamePasswordAuthenticationToken
cannot be cast to com.newcode.meeting.domain.User
答案 0 :(得分:0)
我发现只有一种方法可以吸引用户 从“ event.getUser()”开始,我们得到“ Principal” =>
User connection :
org.springframework.security.authentication.Usernam
ePasswordAuthenticationToken@fe260c00: Principal:
User(id=1, username=admin,
password=$2a$08$VDogbqVQY23gNnLFty/6ReGLecW/bk3oCkUHrsly4HgjBIGRNBSEC,
email=kiy9@gmail.com); Credentials: [PROTECTED]; Authenticated: true; Details:
org.springframework.security.web.authentication.WebAuthenticationDetails@0:
RemoteIpAddress:
0:0:0:0:0:0:0:1; SessionId: 3566D00689DCC01041367983F3132937; Granted Authorities: USER
只有一种方法“ getName”,但它不适合我们,因为我们的名称不是唯一的,并且不可能将“ Principal”转换为“ User”,并且我们使用String来工作)
@EventListener
public void handleWebSocketConnectListener(SessionConnectedEvent event) {
logger.info("Received a new web socket connection:=> "event.getUser().getName());
User user = userRepo.findUserById(getUserId(event.getUser()));
// code
}
private Long getUserId(Principal principal) {
String userString = principal.toString();
int startIndex = userString.indexOf("id=");
int endIndex = userString.indexOf(",", startIndex);
return Long.valueOf(userString.substring(startIndex + 3, endIndex));
}
不是很优雅,但是可以用))