无法从数据库中获取角色以及用户对象

时间:2019-06-10 09:10:53

标签: spring-boot spring-security spring-data-jpa

我正在使用spring boot(2.1.3.RELEASE)创建用户注册流程。借助几篇文章,我能够成功添加用户及其角色,并且用户能够登录系统。问题是,当用户成功登录后,即使我可以在mysql数据库中看到正确的角色映射,身份验证对象也具有空角色(老实地说,当调用findByUserName方法时,我无法确切地了解如何从数据库中提取角色。 下面是我的代码:

实体对象 1. User.java

public class User implements UserDetails {

    private static final long serialVersionUID = 1L;

    public User() {
        //Verification flow 2. set enabled = false
        this.enabled = false;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_unique_number")
    private long id;

    @UniqueUser(groups = UniqueUserOrder.class)
    @Column(name = "username", length = 60,nullable = false, unique = true)
    private String username;

    @Column(name = "email", nullable = false, unique = true)
    private String email;

    @Column(name = "password", nullable = false)
    private String password;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<UserRole> userRoles = new HashSet<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> authorities = new HashSet<>();
        userRoles.forEach(ur -> authorities.add(new Authority(ur.getRole().getName())));
        return authorities;
    }

    public Set<UserRole> getUserRoles() {
        return userRoles;
    }

    public void setUserRoles(Set<UserRole> userRoles) {
        this.userRoles = userRoles;
    }

    ...//OTHER GETTERS AND SETTERS
}
  1. Roles.java

    公共类角色

    {@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;
    
    private String name;
    
    @OneToMany(mappedBy = "role", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<UserRole> userRoles = new HashSet<>();
    
    public Role() {
    
    }
    
    public Role(RolesEnum rolesEnum) {
        this.id = rolesEnum.getId();
        this.name = rolesEnum.getRoleName();
    }
    
    
    public Set<UserRole> getUserRoles() {
        return userRoles;
    }
    
    public void setUserRoles(Set<UserRole> userRoles) {
        this.userRoles = userRoles;
    }
    
    ...//OTHER GETTERS AND SETTERS }
    
  2. UserRole.java

    公共类UserRole {

    public UserRole() {}
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;
    
    public UserRole(User user, Role role) {
        this.user = user;
        this.role = role;
    }
    
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id")
    private User user;
    
    
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "role_id")
    private Role role;
    
    ...//OTHER GETTERS AND SETTERS
    

    }

4.RolesEnum.java

public enum RolesEnum {

    ADMIN(1, "ROLE_ADMIN"),
    BASIC(2, "ROLE_BASIC");

    private final int id;

    private final String roleName;

    ...//OTHER GETTERS AND SETTERS

}

正在创建新用户,如下所示:

...
...
String encryptedPassword = passwordEncoder.encode(adminPassword);
user.setPassword(encryptedPassword);
user.setUsername(adminUsername);
user.setEmail(adminEmail);
user.setUserCreateTime(LocalDateTime.now());

Set<UserRole> userRoles = new HashSet<>();
UserRole userRole = new UserRole();
userRole.setUser(user);
userRole.setRole(new Role(RolesEnum.ADMIN));
userRoles.add(userRole);
user.getUserRoles().addAll(userRoles);

user.setAccountNonLocked(true);
user.setEnabled(true);
user.setAccountNonExpired(true);
user.setCredentialsNonExpired(true);
user = userRepository.save(user);
...
...

此时,已成功添加用户以及数据库中的角色

用户也能够成功登录,但问题是登录后,身份验证对象的角色列表为空 下面是失败的代码

public class SecurityConfig extends WebSecurityConfigurerAdapter {
......
......
private AuthenticationSuccessHandler loginSuccessHandler() {
        return (request, response, **authentication**) -> {
            Collection<? extends GrantedAuthority> authorities
             = authentication.getAuthorities();
            for (GrantedAuthority grantedAuthority : authorities) {
                if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
                    isAdmin = true;
                    break;
                } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
                    isBasic = true;
                    break;
                }
            }

              if (isAdmin) { return "/admin/"; } else if (isBasic) { return
              "/profile.html"; } else { throw new IllegalStateException(); }

            response.sendRedirect("/");
        };
    }
......
......

当我使用Eclipse检查身份验证对象时,角色未从数据库中获取 这是获取user @ Override的代码

public User findByUserName(String username) {
        return userRepository.findByUsername(username);
}

我需要添加一些其他逻辑来与用户一起获取角色,还是由Spring在后台处理它?请让我知道我在做什么错...谢谢

0 个答案:

没有答案