在获取AuthenticatedUser的同时将org.springframework.security.core.userdetails.User
转换为com.***.**.config.security.CustomUserDetail
时,我将异常作为"java.lang.ClassCastException"
。
错误讯息为com.***.**.config.security.CustomUserDetail cannot be cast to com.***.**.config.security.CustomUserDetail
。
源代码:
public static CustomUserDetail getAuthenticatedUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null) {
throw new IllegalArgumentException("Authentication Required.");
}
Object principal = auth.getPrincipal();
User user = (User) principal;
return (CustomUserDetail) user;
}
将user
映射到CustomUserDetail
CustomUserDetail Class
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import com.***.**.globaluser.domain.GlobalUser;
public class CustomUserDetail extends org.springframework.security.core.userdetails.User {
private static final long serialVersionUID = 1L;
private GlobalUser globalUser;
public CustomUserDetail(GlobalUser user,
Collection<? extends GrantedAuthority> authorities) {
super(user.getUsername(), user.getPassword(), authorities);
this.globalUser = user;
}
public CustomUserDetail(GlobalUser user, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities) {
super(user.getUsername(), user.getPassword(), enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, authorities);
this.globalUser = user;
}
public GlobalUser getUserLogin() {
return globalUser;
}
}