Spring Securitiy:从自定义用户检索数据

时间:2015-09-08 19:26:44

标签: java spring spring-security

我试图在Principal中向Spring Security对象添加其他属性。因此我实施了

  • 实现UserDetails
  • 的CustomUser对象
  • 实现UserDetailsService
  • 的CustomUserService

CustomUser:

@Entity
public class CustomUser implements UserDetails { ... }

CustomUserService:

@Service
public class CustomUserService implements UserDetailsService {

    @Autowired
    private CustomUserRepository customUserRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        CustomUser customUser = this.customUserRepository.findByUsername(username);

        return new User(customUser.getUsername(), customUser.getPassword(), true, true, true, true,
            customUser.getAuthorities());
    }
}

最后,我将此添加到 security.xml:

<beans:bean id="customUserDetailsService" class="project.service.CustomUserService"></beans:bean>

<authentication-manager>
    <authentication-provider user-service-ref="customUserDetailsService" />
</authentication-manager>

现在我想通过

检索一些CustomUser特定属性(例如fullName)
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
CustomUser user = (CustomUser) auth.getPrincipal();

但我总是得到ClassCastException

java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to project.entity.CustomUser

有谁知道如何处理这个问题?我的目标是在用户成功登录后在控制器中获取特定用户数据。到目前为止,除了检索CustomUser属性外,一切正常。 谢谢!

1 个答案:

答案 0 :(得分:0)

作为CustomUser implements UserDetails

但是你要返回新用户(...)并转换为类型不匹配的CustomUser,因此你得到了ClassCastException。 您必须直接返回CustomUser类型,如下所示。

   @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        return this.customUserRepository.findByUsername(username);

编辑: 而不是CustomUser实现UserDetails,您必须扩展User对象并填写详细信息并返回如下。您也可以将UserEntity对象和CustomUser对象分开

public class CustomUser extends org.springframework.security.userdetails.User {.....}

@Entity
public class UserEntity {...}

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

 UserEntity userEntity = this.customUserRepository.findByUsername(username);

 CustomUser customUser = new CustomUser( userEntity.getUsername(), userEntity.getPassword()........);

 return customUser;
}

在此之后,您可以访问

 CustomUser customUser = (CustoomUser) authentication.getPrincipal();