Роли не извлекаются из базы данных вместе с объектом пользователя - PullRequest
0 голосов
/ 10 июня 2019

Я создаю поток регистрации пользователей с весенней загрузкой (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
}

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 }

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, роли не извлекаются из базы данных. Вот код для извлечения пользователя @ Override

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

Нужно ли добавить некоторую дополнительную логику визвлекать роли вместе с пользователем или Spring обрабатывает их за сценой?Пожалуйста, дайте мне знать, что я делаю не так здесь ... Спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...