Java Spring安全性:在使用UserDetailsService时可以访问当前用户原则
我有一个userDetailsService类型的AuthenticationProvider,如下所示:Java Spring安全性:在使用UserDetailsService时可以访问当前用户原则,java,authentication,spring-security,Java,Authentication,Spring Security,我有一个userDetailsService类型的AuthenticationProvider,如下所示: public class CustomUDS implements UserDetailsService { @Override public UserDetails loadUserByUsername(String clientId) throws UsernameNotFoundException, DataAccessException {
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);
}
}
对象值将是字符串
“org.springframework.security.core.userdetails。User@db343434:用户名
……”
我无法将返回对象转换为User或UserDetails
现在,如何访问用户的用户名?因此,请尝试以下方法获取用户名:
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = userDetails.getUsername();
什么??在运行时,我需要在我的web应用程序的几个点中输入用户的用户名!我说,我无法将字符串转换为UserDetails对象,它将返回类型转换异常。@M2E67为什么认为
SecurityContextHolder.getContext().getAuthentication().getPrincipal()
返回字符串?你试过上面的代码吗?原则?我想你指的是校长。
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = userDetails.getUsername();