부트캠프 기록/Section4

[Spring Security] JWT 자격 증명을 위한 로그인 인증 구현

bbangduck 2022. 11. 26. 21:05

1. 사용자의 로그인 인증 성공 후, JWT가 클라이언트에게 전달되는 과정

  1. 클라이언트가 서버 측에 로그인 인증 요청(Username/Password를 서버 측에 전송)
  2. 로그인 인증을 담당하는 Security Filter(JwtAuthenticationFilter)가 클라이언트의 로그인 인증 정보 수신
  3. Security Filter가 수신한 로그인 인증 정보를 AuthenticationManager에게 전달해 인증 처리를 위임
  4. AuthenticationManager가 Custom UserDetailsService(MemberDetailsService)에게 사용자의 UserDetails 조회를 위임
  5. Custom UserDetailsService(MemberDetailsService)가 사용자의 크리덴셜을 DB에서 조회한 후, AuthenticationManager에게 사용자의 UserDetails를 전달
  6. AuthenticationManager가 로그인 인증 정보와 UserDetails의 정보를 비교해 인증 처리
  7. JWT 생성 후, 클라이언트의 응답으로 전달

 

2. JWT 자격 증명을 위한 로그인 인증 구현

1️⃣ Custom UserDetailsService 구현

 

데이터베이스에서 사용자의 크리덴셜을 조회한 후, 조회한 크리덴셜을 AuthenticationManager에게 전달하는 Custom UserDetailsService를 구현

(MemberDetails는 MemberDetailService 의 이너클래스입니다.)

 

 

2️⃣ 로그인 인증 정보 역직렬화(Deserialization)를 위한 LoginDTO 클래스 생성

클라이언트가 전송한 Username/Password 정보를 Security Filter에서 사용할 수 있도록 역직렬화(Deserialization)하기 위한 DTO 클래스

 

 

3️⃣ JWT를 생성하는 JwtTokenizer 구현

로그인 인증에 성공한 클라이언트에게 JWT를 생성 및 발급하고 클라이언트의 요청이 들어올 때 마다 전달된 JWT를 검증하는 클래스

 

 

 

4️⃣ 로그인 인증 요청을 처리하는 Custom Security Filter 구현

클라이언트의 로그인 인증 정보를 직접적으로 수신하여 인증 처리의 엔트리포인트(Entrypoint) 역할을 하는 클래스

 

 

 

5️⃣ Custom Filter 추가를 위한 SecurityConfiguration 설정 추가

 

Custom Filter인 JwtAuthenticationFilter 의 구현이 끝났다면 JwtAuthenticationFilter 를 Spring Security Filter Chain에 추가

 

 

 

3. 로그인 인증 성공 및 실패에 따른 추가 처리

1️⃣ AuthenticationSuccessHandler 구현

2️⃣ AuthenticationFailureHandler 구현

 

3️⃣ AuthenticationSuccessHandler와 AuthenticationFailureHandler를 JwtAuthenticationFilter에 등록(SecurityConfiguration에서)

 

4️⃣ jwtAuthenticationFilter에서 AuthenticationSuccessHandler 호출

AuthenticationFailureHandler는 별도의 코드를 추가하지 않아도 로그인 인증에 실패하면 구현했MemberAuthenticationFailureHandler의 onAuthenticationFailure() 메서드가 알아서 호출