Reputation: 571
I need to access currently logged-in user details (id or email address) in Controller. This is how I am trying to do so right now, and this doesn't work.
ApplicationUser
is an @Entity
in database.
UserDetailsService:
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private ApplicationUserRepository applicationUserRepository;
public UserDetailsServiceImpl(ApplicationUserRepository applicationUserRepository) {
this.applicationUserRepository = applicationUserRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
ApplicationUser applicationUser = applicationUserRepository.findByUsername(username);
if (applicationUser == null) {
throw new UsernameNotFoundException(username);
}
return builtCustomUser(applicationUser);
}
private User builtCustomUser(ApplicationUser applicationUser) {
String username = applicationUser.getUsername();
String password = applicationUser.getPassword();
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
MyUser myUser = new MyUser(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, emptyList());
return myUser;
}
}
Custom User class:
public class MyUser extends User implements UserDetails {
public MyUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
public MyUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
}
That's how I am trying to access it in Controller:
MyUser mu = (MyUser) authentication.getPrincipal();
And this is error:
java.lang.ClassCastException: class java.lang.String cannot be cast to class MyUser
Upvotes: 0
Views: 550
Reputation: 2643
On this code, actual type of Authentication
is UsernamePasswordAuthenticationToken
, and return type of getPrincipal()
is String
, username.
You can set any other Authentication
implementation instead of UsernamePasswordAuthenticationToken
to SecurityContext
, and principal type is free(so you can set MyUser
), too.
Upvotes: 1