Spring Security:使用UserDetailesService时可以访问当前用户原则

时间:2017-12-27 07:40:41

标签: java authentication spring-security

我有一个类型为userDetailsS​​ervice的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。

现在,我该如何访问用户的用户名?

1 个答案:

答案 0 :(得分:1)

所以试试这个来获取用户名:

UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = userDetails.getUsername();