我有一个类型为userDetailsService的AuthenticationProvider,如下所示:
public class CustomUDS implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String clientId) throws UsernameNotFoundException, DataAccessException {
ClientDetails client=clientDetailsService.loadClientByClientId(clientId);
String password=client.getClientSecret();
boolean enabled=true;
boolean accountNonExpired=true;
boolean credentialsNonExpired=true;
boolean accountNonLocked=true;
List<GrantedAuthority> authorities=new ArrayList<GrantedAuthority>();
GrantedAuthority roleClient=new SimpleGrantedAuthority("ROLE_CLIENT");
authorities.add(roleClient);
return new User(clientId,password,enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,authorities);
}
}
当用户登录并使用follow语句获取用户的用户名时,它返回User class的字符串值:
Object object = SpringSecurityContext.getcontext().getAuthentication.getPrinciple();
对象值将为字符串
“org.springframework.security.core.userdetails.User@db343434:用户名 ......“
我无法将返回对象转换为User或UserDetails。
现在,我该如何访问用户的用户名?
答案 0 :(得分:1)
所以试试这个来获取用户名:
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = userDetails.getUsername();