마트철수

[072] API 로그인 및 사용자 인증 본문

KB IT's Your Life/교육

[072] API 로그인 및 사용자 인증

마트스 2024. 8. 22. 18:37

 

2024.08.22(목)
 
Spring 13일차

 


 

Spring


 

PART01

  • CH02. 스프링의 특징과 의존성 주입
  • CH03.1 스프링 MVC의 기본 구조
  • CH03.2 스프링 MVC의 Controller 1
  • CH03.3 스프링 MVC의 Controller 2
  • CH03.4 SpringLegacy 업데이트
  • CH04.1 스프링과 MySQL Database
  • CH04.2 MyBatis와 스프링 연동
  • CH05.1 영속, 비즈니스 계층의 CRUD 구현
  • CH05.2 비즈니스 계층
  • CH05.3 프레젠테이션(웹) 계층의 CRUD 구현
  • CH06.1 화면 처리
  • CH06.2 File, Upload, Download

Part 4. Rest API

  • CH07 Rest Controller
  • CH08.1 OpenApi
  • CH08.2 RestTemplate
  • Spring Security
  • CH10.2 로그인과 로그아웃 처리
  • CH10.3 member
  • CH10.4 UserDetails 사용하기
  • CH11 Api Server Security 기본 설정
  • CH11.1 JWT의 이해
  • CH11.2 JWT 자바 라이브러리
  • CH12.1 API 로그인
  • CH12.2 사용자 인증

 


CH12.1 API 로그인

 

API 로그인

 

JsonResponse

  • 로그인 결과를 필터에서 직접 Json 응답하기 위한 유틸리티 클래스

 

JsonResponse

 

JwtUsernamePasswordAuthenticationFilter

  • 로그인 url과 로그인 성공/실패 처리기를 등록
  • AuthenticationManager의 인증 절차는 formLogin 때와 동일
  • 인증 성공/실패 여부에 따라..
    • LoginSuccessHandler
    • LoginFailureHandler
  • 주의사항
    • AuthenticationManager는 SecurityConfig가 생성된 이후에 Bean으로 등록
    • SecurityConfig에서 @Autowired로 연결해야 함

 

JwtUsernamePasswordAuthenticationFilter

 

 

  • LoginSuccessHandler
    • 토큰 + 사용자 기본 정보를 묶어서 AuthResultDTO 구성
@Log4j
@Component
@RequiredArgsConstructor
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    private JwtProcessor jwtProcessor;
    private AuthResultDTO makeAuthResult(CustomUser user) {
        String username = user.getUsername();
// 토큰 생성
        String token = jwtProcessor.generateToken(username);
// 토큰 + 사용자 기본 정보 (사용자명, ...)를 묶어서 AuthResultDTO 구성
        return new AuthResultDTO(token, UserInfoDTO.of(user.getMember()));
    }

 

  • LoginFailureHandler
    • 에러 메세지만 구현하면 됨 (AuthenticationFailureHandler)
    • HttpStatus.UNAUTHORIZED = 402 error
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException, IOException {
        JsonResponse.sendError(response, HttpStatus.UNAUTHORIZED, "사용자 ID 또는 비밀번호가 일치하지 않습니다.");
    }
}

 

  • Security 연결 작업
    ...
    @Autowired
    private JwtUsernamePasswordAuthenticationFilter jwtUsernamePasswordAuthenticationFilter;
	
    ...
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 한글 인코딩 필터 설정
        http.addFilterBefore(encodingFilter(), CsrfFilter.class)
        // 로그인 인증 필터
            .addFilterBefore(jwtUsernamePasswordAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

# filter, handler가 Security와 직접적인 관련이 있음

# 나머지는 유틸리티 클래스

 

 

사용자 인증

 

JwtAuthenticationFilter

  • 모든 요청에 대해서 헤더에 토큰이 있는지 검사
  • 있으면 '로그인한 상태'라고 인식
    • Authorization 헤더 항목 조사
      • Authoruzation: Bearer <jwt 토큰 문자열>
  • 토큰의 유효성 검사
    • 토큰이 유효하면 SecurityCibtextHolder에 사용자 로그인 정보 설정
  • OncePerrequestFilter 상속
    • 컨트롤러가 forward 했을 때 필터를 다시 통과하게 됨
      → 이미 보안 필터는 통과했는데, 또 통과하게 됨

 

JwtAuthenticationFilter

 

 

  • 인증 예외 처리
    • 토근 처리시 예외 발생 가능
      • 여러 예외 중 토큰 만기 예외인 경우 401 인증 에러로 리턴
      • 그 외의 예외는 일잔 예외 메시지로 처리

 

  • Test
    • 10분 경과시 ..
    • 해당 요류 확인 !!

 

 

 


 

다음주부터는 드디어 Vue + Spring 연동 과정에 대해 배울 예정!

 

Vue로 Client, Spring은 Backend로!

접근은 모두 api를 사용해서 구현한다고 한다.

 

회원가입을 포함해서 회원관리까지 ..