CustomUserDetailsService

jb kim·2022년 3월 6일
0

REST API 블로그 앱

목록 보기
46/65

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

profile
픽서

0개의 댓글