我无法获取除姓名以外的用户,但该姓名并非 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
最佳答案
我发现只有一种方法来获取用户 由于“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”是不可能的,我们使用字符串)
@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));
}
不太优雅但有效))
关于java - 委托(delegate)人获取用户ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59214549/