Spring Security:使用UserDetailsS ervice时可以访问当前用户主体

问题描述 投票:-2回答:1

我有一个类型为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类的字符串值:

Object object = SpringSecurityContext.getcontext().getAuthentication.getPrinciple();

对象值将是字符串

“org.springframework.security.core.userdetails.User@db343434:用户名....”

我无法将返回对象转换为User或UserDetails。

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

java authentication spring-security
1个回答
1
投票

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

UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = userDetails.getUsername();
© www.soinside.com 2019 - 2024. All rights reserved.