我讓這個類UserPrincipal獲得我自定義的Hibernate User類的用戶ID。java.lang.ClassCastException:org.springframework.security.core.userdetails.User不能轉換爲UserPrincipal
public class UserPrincipal extends org.springframework.security.core.userdetails.User {
public User getUser() {
return user;
}
public UserPrincipal(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities, User user) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.user = user;
}
private final User user;
}
然而,當我使用它是這樣的:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User user = ((UserPrincipal) principal).getUser();
我收到以下錯誤:
java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to UserPrincipal
我覺得有一個在我實現了構造的方式錯誤,但我不確定。
或者它是否與我登錄用戶的方式不匹配?我正在使用Spring Security。
所以我只需要垂頭喪氣UserPrincipal給用戶? – jarvan
無法執行以下操作:(org.springframework.security.core.userdetails.User)principal = SecurityContextHolder.getContext()。getAuthentication()。getPrincipal(); – jarvan
等待,我試圖做的全部事情是從自定義類User獲取userId。如果我需要創建並傳遞一個帶有userId的User實例,那就會破壞我想要做的事情的全部內容。 – jarvan