Spring security Userdetails 无法转换为我自己的用户实现

Posted

技术标签:

【中文标题】Spring security Userdetails 无法转换为我自己的用户实现【英文标题】:Spring security Userdetails cannot be cast to my own user implementation 【发布时间】:2021-12-20 20:47:27 【问题描述】:

我有一个User 类,它实现了弹簧安全UserDetails。但是,在对登录请求进行身份验证期间,它会给出一个 ClassCastException,即不能将 UserDetails 强制转换为我的 User 类。

完整的错误:

java.lang.ClassCastException: 类 org.springframework.security.core.userdetails.User 不能被强制转换为 类 nl.teamrepositories.vliegmaatschappij.security.domain.User (org.springframework.security.core.userdetails.User 未命名 加载器“app”的模块; nl.teamrepositories.vliegmaatschappij.security.domain.User 在 loader的未命名模块 org.springframework.boot.devtools.restart.classloader.RestartClassLoader @6ef8cb6)

用户:

package nl.teamrepositories.vliegmaatschappij.security.domain;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.Collection;
import java.util.List;

@Entity
@Table(name = "users")
@Getter @Setter @NoArgsConstructor
public class User implements UserDetails 

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false, unique = true)
    private String firstName;
    private String lastName;
    private String username;
    private String password;

    private boolean enabled;
    private boolean tokenExpired;

    public User(String firstName, String lastName, String username, String password) 
        this.firstName = firstName;
        this.lastName = lastName;
        this.username = username;
        this.password = password;
    

    @ManyToMany
    @JoinTable(
            name = "users_roles",
            joinColumns = @JoinColumn(
                    name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(
                    name = "role_id", referencedColumnName = "id"))
    private Collection<Role> roles;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() 
        return List.of(new SimpleGrantedAuthority("ROLE_USER"));
    

    @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 true;
    

在 JwtAuthenticationFilter 中:

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                        FilterChain filterChain, Authentication authentication) 
    User user = (User) authentication.getPrincipal(); // this is where the error occurs
    // more code

我不明白为什么我的 User 类不能转换为 Spring 的 UserDetails 类。

我应该改变什么?

提前致谢。

【问题讨论】:

【参考方案1】:

JwtAuthenticationFilter 中检查您的导入。我猜你正在使用import org.springframework.security.core.userdetails.User 而不是你自己的班级import nl.teamrepositories.vliegmaatschappij.security.domain.User

import nl.teamrepositories.vliegmaatschappij.security.domain.User;
(...)

public class JwtAuthenticationFilter 
    (...)

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                            FilterChain filterChain, Authentication authentication) 
        User user = (User) authentication.getPrincipal(); // this is where the error occurs
        // more code
    

无论是在这里还是在代码中的其他地方,您都使用了错误的 User 类(Spring 类而不是您的类)。

【讨论】:

以上是关于Spring security Userdetails 无法转换为我自己的用户实现的主要内容,如果未能解决你的问题,请参考以下文章

Spring mvc / security:从spring security中排除登录页面

Spring Security:2.4 Getting Spring Security

没有 JSP 的 Spring Security /j_spring_security_check

Spring-Security

Spring Security 登录错误:HTTP 状态 404 - /j_spring_security_check

未调用 Spring Security j_spring_security_check