설명출처 : https://to-dy.tistory.com/86
UserDetailsService VS UserDetails
(1) UserDetails
(2) UserDetailsService
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserAuthDAO userAuthDAO;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
CustomUserDetails user = userAuthDAO.getUserById(username);
if(user==null) {
throw new UsernameNotFoundException(username);
}
return user;
}
}
passwordEncoder 추가
@Configuration
public class PasswordEncoderConfig {
@Bean
public PasswordEncoder passwordEncoder(){
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
(!passwordEncoder.matches(password, loginUser.getPassword()))
같은 코드로 지금 입력된 비밀번호와, 로그인한 유저의 비밀번호와 같은 지 유무 파악해서 적절한 비번 넣었는지 알기 가능
UserEntity 추가
@Entity
@Table(name = "USER_ENTITY")
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String username;
@Column
private String password;
@Column
private String nickname;
@Column
private String role;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
@Service
public class CustomUserDetailsService implements UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public CustomUserDetailsService(
@Autowired UserRepository userRepository,
@Autowired PasswordEncoder passwordEncoder
) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
final UserEntity testUserEntity = new UserEntity();
testUserEntity.setUsername("entity_user");
testUserEntity.setPassword(passwordEncoder.encode("test1pass"));
this.userRepository.save(testUserEntity);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final UserEntity userEntity = userRepository.findByUsername(username);
return new User(username, userEntity.getPassword(), new ArrayList<>());
}
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final UserEntity userEntity = userRepository.findByUsername(username);
return new User(username, userEntity.getPassword(), new ArrayList<>());
}