import com.blog.app.entity.Role;
import com.blog.app.entity.User;
import com.blog.app.repository.UserRepository;
@Service
public class CustomUserDetailsService implements UserDetailsService {
private UserRepository userRepository;
public CustomUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String usernameOrEmail) throws UsernameNotFoundException {
User user = userRepository.findByUsernameOrEmail(usernameOrEmail, usernameOrEmail)
.orElseThrow(() -> new UsernameNotFoundException( usernameOrEmail + " username 또는 email 의 유저가 없습니다."));
return new org.springframework.security.core.userdetails.User(user.getEmail(),
user.getPassword(), mapRolesToAuthorities(user.getRoles()));
}
private Collection< ? extends GrantedAuthority> mapRolesToAuthorities(Set<Role> roles){
return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
}
}
참고
https://programmer93.tistory.com/68