You should override loadUserByUsername()
method of your DatabaseUserRepository
class as follows:
@Primary
@Component("UserRepository")
public class DatabaseUserRepository extends AbstractDatabaseUserRepository<User> {
private final UnconstrainedDataManager dataManager;
private final RoleAssignmentRepository roleAssignmentRepository;
private final ResourceRoleRepository resourceRoleRepository;
private final RowLevelRoleRepository rowLevelRoleRepository;
public DatabaseUserRepository(UnconstrainedDataManager dataManager,
RoleAssignmentRepository roleAssignmentRepository,
ResourceRoleRepository resourceRoleRepository,
RowLevelRoleRepository rowLevelRoleRepository) {
this.dataManager = dataManager;
this.roleAssignmentRepository = roleAssignmentRepository;
this.resourceRoleRepository = resourceRoleRepository;
this.rowLevelRoleRepository = rowLevelRoleRepository;
}
@Override
public User loadUserByUsername(String username) throws UsernameNotFoundException {
List<User> users = dataManager.load(User.class)
.query("lower(e.username) = ?1", username.toLowerCase())
.list();
if (!users.isEmpty()) {
User user = users.get(0);
if (user != null) {
((AcceptsGrantedAuthorities) user).setAuthorities(createAuthorities(user.getUsername()));
}
return user;
} else {
throw new UsernameNotFoundException("User not found");
}
}
private Collection<? extends GrantedAuthority> createAuthorities(String username) {
return roleAssignmentRepository.getAssignmentsByUsername(username).stream()
.map(this::createAuthority)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
private GrantedAuthority createAuthority(RoleAssignment roleAssignment) {
GrantedAuthority authority = null;
if (RoleAssignmentRoleType.RESOURCE.equals(roleAssignment.getRoleType())) {
ResourceRole role = resourceRoleRepository.findRoleByCode(roleAssignment.getRoleCode());
if (role != null) {
authority = RoleGrantedAuthority.ofResourceRole(role);
}
} else if (RoleAssignmentRoleType.ROW_LEVEL.equals(roleAssignment.getRoleType())) {
RowLevelRole role = rowLevelRoleRepository.findRoleByCode(roleAssignment.getRoleCode());
if (role != null) {
authority = RoleGrantedAuthority.ofRowLevelRole(role);
}
}
return authority;
}
// ...