UserDetailsService

'인증'하기 위해서 유저와 관리자 데이터를 가져온다.

 

UserDetailsServiceImpl 는

유저와 관리자의 정보를 읽어오는 클래스

 

 

[ SecurityConfig ]

 

ctrl + space 해서 configure 인증메서드는 AuthenticationManagerBuilder 자동생성

 

private UserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // 인증(로그인) 메서드 구현하기 위해 userDetailsService 로 유저의 username,password,role등 을 찾아서 인증
    auth
        .userDetailsService(userDetailsService)
        .passwordEncoder(encoder());	
}

 

.userDetailsService

▶ '인증'하기 위해서 유저의 username password role 등을 찾아서 인증해줌

 

 

private UserDetailsService userDetailsService;  

▶  UserDetailsService 객체를 구현하는 클래스 UserDetailsServiceImpl 도 만들어준다.

 


[ UserDetailsServiceImpl ]

 

@Service 어노테이션 

 

유저와 관리자의 정보를 읽어오는 메서드(loadUserByUsername) 자동생성하기 

 

@Service
public class UserDetailsServiceImpl implements UserDetailsService{

	@Autowired
	private UserRepository userRepo;
	
	@Autowired
	private AdminRepository adminRepo;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 유저DB에서 필요한 유저,관리자 정보를 읽어온다. (입력파라메터는 username)
		
		User user = userRepo.findByUsername(username);
		Admin admin = adminRepo.findByUsername(username);
		
		if(admin != null) return admin; // 먼저! 관리자가 있으면 관리자로 리턴
		if(user != null) return user;	// 유저가 있으면 유저로 리턴
		
		//관리자 유저 모두 없으면
		throw new UsernameNotFoundException("유저 " + username + "이 없습니다.");
		
	}
}

username으로 유저,관리자 정보 읽어오기

관리자가 먼저 리턴 되도록하기

유저나 관리자에도  없으면  throw new UsernameNotFoundException

 

 

 

 

SecurityConfig 에서

.userDetailsService(userDetailsService)
.passwordEncoder(encoder());

userDetailsService를 통해 유저 또는 관리자를 찾아 DB에 있는 알 수 없게 암호화된 것을 다시 풀기위한 객체

 

 

 

 


 

오류

A UserDetailsService must be set

UserDetailsService 관련된 모든 코드를 다시 살펴보자

 

[ SecurityConfig ]
@Autowired
private UserDetailsService userDetailsService;

 

 

해결

@Autowired 가 빠져있었다!

반응형
LIST

+ Recent posts