개발 공부 기록

[SpringBoot] 이메일 인증 코드 유효시간 설정 및 이메일 인증하기 본문

Spring/Development Log

[SpringBoot] 이메일 인증 코드 유효시간 설정 및 이메일 인증하기

나만없서고냥이 2024. 3. 17. 05:28

이전에 아래 포스팅에서 이메일을 인증할 메일(이메일 인증 코드)을 발송하는 기능에 대해서 구현해보았습니다.

https://jieeeuun.tistory.com/69

 

[SpringBoot] 이메일 발송 기능 구현하여 이메일 인증 코드 발송하기

Gmail을 이용하여 회원가입 시 사용자가 입력한 이메일로 이메일 인증 코드를 발송하는 기능을 구현해보겠습니다. ✔️ 발신 이메일 계정 설정하기 Google 계정 관리에 들어가 보안 탭을 누른 후 2

jieeeuun.tistory.com

그렇다면 이메일 인증 코드의 유효시간을 5분으로 설정하고, 5분이 지나면 해당 코드는 무효가 되도록 구현해보겠습니다. 또한 사용자가 입력한 인증 코드를 받아, 올바르게 입력했을 경우 이메일 인증이 완료되는 것까지 구현하도록 하겠습니다.

 


✔️ application.yml 설정

저번 포스팅에서 application.yml에 이메일과 관련된 부분을 설정했습니다. 여기에 이메일 인증 코드의 유효시간을 설정해줍니다.

spring:
  mail:
    host: smtp.gmail.com
    port: 587
    username: ${mail.username}
    password: ${mail.password}
    properties:
      mail:
        smtp:
          auth: true
          timeout: 5000
          starttls:
            enable: true
    auth-code-expiration: 300000  #5분

 


✔️ EmailService.java

우선, 우리가 발송한 이메일 인증 코드를 redis에 저장합니다.

private MimeMessage createCertificationEmail(String email) {
        try {
            MimeMessage message = emailSender.createMimeMessage();

            certificationCode = createCertificationCode();
            redisService.setValues(AUTH_CODE_KEY + email, certificationCode, authCodeExpiration);

            String title = "[Bobjeong] 이메일 인증 번호 안내";
            String text = "<table align=\"center\" width=\"670\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-top: 2px solid #583101; border-right: 1px solid #e7e7e7; border-left: 1px solid #e7e7e7; border-bottom: 1px solid #e7e7e7;\">\n" +
                             ...        
                    "<tbody><tr><td height=\"49\" style=\"text-align: center; color: #fff\">인증번호 : <span>" + certificationCode + "</span></td></tr>\n" +
                             ...        
                    "    </tbody></table>";
                    
            message.addRecipients(RecipientType.TO, email);
            message.setSubject(title);
            message.setText(text, "utf-8", "html");

            return message;
        } catch (MessagingException e) {
            throw new RuntimeException();
        }
    }

 

그리고 사용자에게 받은 인증 코드와 redis에 저장된 인증 코드를 비교하여 인증하는 방식으로 설계합니다.

public void checkEmailAuthCode(String email, String authCode) {
        String redisAuthCode = redisService.getValues(AUTH_CODE_KEY + email);
        if (redisService.checkExistsValue(redisAuthCode) || redisAuthCode.equals(authCode)) {
            throw new CustomException(CustomResponseCode.INCORRECT_AUTHENTICATION_CODE);
        }

        redisService.deleteValues(AUTH_CODE_KEY + email);
}

 


✔️ EmailCodeVerificationRequest.java

이메일 인증에 쓰일 DTO를 작성해줍니다.

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class EmailCodeVerificationRequest {
    private String email;
    private String authCode;
}

 


✔️ EmailController.java

이제 컨트롤러에서 EmailService를 호출하여 이메일 인증을 진행합니다.

@GetMapping("/signup/check/email-auth-code")
public ResponseEntity<BaseResponse<String>> checkEmailAuthCode(@RequestBody EmailCodeVerificationRequest emailCodeVerificationRequest) {
    emailService.checkEmailAuthCode(emailCodeVerificationRequest);
    return ResponseEntity.ok().body(BaseResponse.createSuccessWithNoContent(CustomResponseCode.SUCCESS));
}