java.lang.ClassCastException : class org. springframework.security.core.userdetails.User 无法转换为类

标签 java spring spring-boot spring-mvc spring-security

我的 Spring Boot 应用程序有问题。我正在发送获取 key 的请求,但收到错误


java.lang.ClassCastException: class org.springframework.security.core.userdetails.User cannot be cast to class com.spring.springBlogProject.model.User (org.springframework.security.core.userdetails.User and com.spring.springBlogProject.model.User are in unnamed module of loader 'app')
    at com.spring.springBlogProject.security.JwtProvider.generateToken(JwtProvider.java:28) ~[classes/:na]

我不明白问题是什么,我是第一次使用 spring。我发现接收到的数据无法简化为我创建的类。可能是什么问题呢?以下是我的类(class),我使用的是 Spring Boot (v2.3.1.RELEASE)

感谢您的帮助。

public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       User user = userRepository.findByUsername(username).orElseThrow(()->
                new UsernameNotFoundException("No user found with " + username));

        return new org.springframework.security.core.userdetails.User(user.getUsername(),
                user.getPassword(),
                true,true,true,true,
                getAuthorities("ROLE_USER"));
    }

    private Collection<? extends GrantedAuthority> getAuthorities(String role_user) {
        return Collections.singletonList(new SimpleGrantedAuthority(role_user));
    }
}
@Table
public class User {
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String username;

    @Column
    private String password;

    @Column
    private String email;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
public class AuthService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtProvider jwtProvider;

    public void signUp(RegisterRequest registerRequest) {
        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(encodePassword(registerRequest.getPassword()));
        user.setEmail(registerRequest.getEmail());

        userRepository.save(user);
    }

    private String encodePassword(String password) {
        return passwordEncoder.encode(password);
    }

    public String login(LoginRequest loginRequest) {
       Authentication authenticate =  authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(),
                loginRequest.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        return jwtProvider.generateToken(authenticate);
    }
}

最佳答案

您必须按照以下方式在 UserDetails 中将其转换,

public class JwtUser implements UserDetails {

    private final long id;
    private final String email;
    private final String phoneNo;
    private final String username;
    private final String password;
    private final boolean enabled;
    private final Collection<? extends GrantedAuthority> authorities;

    public JwtUser(long userId, String email, String username, String phoneNo, String password, Boolean enabled,  Collection<? extends GrantedAuthority> authorities) {
        this.id = userId;
        this.email = email;
        this.phoneNo = phoneNo;
        this.username = username;
        this.password = password;
        this.enabled = enabled;
        this.authorities = authorities;
    }

    public long getId() {
        return id;
    }

    public String getEmail() {
        return email;
    }

    public String getPhoneNo() {
        return phoneNo;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}

替换:

return new org.springframework.security.core.userdetails.User(user.getUsername(),
                user.getPassword(),
                true,true,true,true,
                getAuthorities("ROLE_USER"));

与:

return new JwtUser(user.get().getUserId(), user.get().getEmail(), user.get().getUsername(),
                user.get().getPhoneNo(), user.get().getPassword(), Boolean.TRUE, grantedAuthoritySet(user.get().getAuthorities()));

关于java.lang.ClassCastException : class org. springframework.security.core.userdetails.User 无法转换为类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62457056/

相关文章:

java - 在字符串问题中存储 XPath 查询 xml

java - 合并多个表的 SQL 语法

java - 通过AOP拦截重载方法

jquery - 如何在JSP页面中实时显示通知

java - Spring Kafka - 选择 @TopicPartition 会停用组中的消费者

java - 9.x 的 jetty-all-server 在哪里?

java - 如何使用 REST 模板中的 Json 并将每个元素映射到 Spring Boot 中的另一个 Json

spring - 如何在main函数中获取ApplicationContext - Spring boot

java - 将图像与实体一起保存在数据库中

java - 如何在 Java 中求解字符串中的基本数学方程?