【问题标题】:Spring Security : Could access to current user principle when using UserDetailesServiceSpring Security:使用 UserDetailsS​​ervice 时可以访问当前用户主体
【发布时间】:2018-06-07 20:47:37
【问题描述】:

我有一个 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);
        }
}

当用户登录并使用以下语句获取用户的用户名时,它返回用户类的字符串值:

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

对象值将是字符串

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

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

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

【问题讨论】:

  • 原理?我想你的意思是校长。

标签: java authentication spring-security


【解决方案1】:

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

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

【讨论】:

  • 什么??在运行时,我需要在我的 Web 应用程序的多个点使用用户的用户名!
  • 我说的是,我无法将字符串转换为 UserDetails 对象,它会返回类型转换异常。
  • @M2E67 为什么你认为SecurityContextHolder.getContext().getAuthentication().getPrincipal() 返回一个字符串?上面的代码你试过了吗?
猜你喜欢
  • 2012-06-11
  • 2016-01-24
  • 2011-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 2015-06-02
相关资源
最近更新 更多