主体获取用户 ID



我无法获得除其名称以外的用户,但该名称不是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?

如果我尝试用户用户 = 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 (("我们得到"主体"=>

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",但它不适合我们,因为我们的名字不是唯一的,将"主体"变成"用户"是不可能的,我们使用字符串(

@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));
}

不是很优雅,但有效((

最新更新