카카오 로그인 시 DB에 정보가 없으면 회원가입 진행 후 로그인을 진행하는 서비스를 생성하였다.

하지만 회원가입 진행 후 로그인이 정상적으로 작동하지 않는 상황이 발생하였다.

String kakaoUsername =
		 kakaoProfile.getKakao_account().getEmail() + "_" + kakaoProfile.getId();
String kakaoEmail = kakaoProfile.getKakao_account().getEmail();
String kakaoPassword = cosKey;

User kakaoUser = User.builder()
        .username(kakaoUsername)
        .password(kakaoPassword)
        .email(kakaoEmail).build();

if(!userService.isExistUser(kakaoUsername)) {
    System.out.println("=======================회원가입 진행========================");
    userService.join(kakaoUser);
}

System.out.println("=======================로그인 진행========================");
Authentication authentication = authenticationManager.authenticate(
        new UsernamePasswordAuthenticationToken(kakaoUsername, kakaoUser.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);

Untitled

회원 가입 진행 전과 후, kakaoUser 객체의 패스워드가 다른지 테스트 해보았다.

System.out.println("회원가입 진행 전 패스워드: " + kakaoUser.getPassword());
if(!userService.isExistUser(kakaoUsername)) {
    System.out.println("=======================회원가입 진행========================");
    userService.join(kakaoUser);
}
System.out.println("회원가입 진행 후 패스워드: " + kakaoUser.getPassword());
회원가입 진행 전 패스워드: cos1234
=======================회원가입 진행========================
회원가입 진행 후 패스워드: $2a$10$OE5hOZ1rmKYmQC7z3t108eqd7ga2oCcwK0s.esOPZuUmGXTHjFt7K

회원 가입 진행 후, kakaoUser 객체의 패스워드는 인코딩 된 문자였다.

kakaoUser 객체가 영속화되어 이런 현상이 일어나는 건가 했지만

회원 가입 로직에서 객체를 전달받아 인코딩을 해주어 setter를 통해 저장하여 일어나는 현상이었다.

@Transactional
public void join(User user) {
    String encPassword = encoder.encode(user.getPassword());
    user.setPassword(encPassword);
    user.setRole(RoleType.USER);

    userRepository.save(user);
}

user 객체를 깊은 복사를 이용하여 새로운 객체로 생성후 저장할까 생각했지만 불필요한 코드의 추가가 필요하여 application.yml에 카카오 로그인 전용 로그인 키를 추가하여 이를 사용하도록 코드를 작성하였다.

@Value("${cos.key}")
private String cosKey;
String kakaoUsername = kakaoProfile.getKakao_account().getEmail() + "_" + kakaoProfile.getId();

if(!userService.isExistUser(kakaoUsername)) {
    User kakaoUser = User.builder()
            .username(kakaoUsername)
            .password(kakaoProfile.getKakao_account().getEmail())
            .email(cosKey).build();

    userService.join(kakaoUser);
}

System.out.println("=======================로그인 진행========================");
Authentication authentication = authenticationManager.authenticate(
        new UsernamePasswordAuthenticationToken(kakaoUsername, cosKey));
SecurityContextHolder.getContext().setAuthentication(authentication);