Spring/인증_인가
[Spring] JWT를 이용한 인증,인가 동작 원리
초코chip
2024. 11. 11. 23:02
Spring - 인증 과정 (첫 로그인 과정)

1. 클라이언트 요청- 클라이언트가 `/api/auth/login` 엔드포인트로 AuthRequest(username, password)를 POST 요청2. 내장 Tomcat 서버- Tomcat 서버가 요청을 처리하여 AuthController로 전달합3. AuthController - authenticate 호출- AuthController는 AuthenticationManager를 사용해 인증을 시도- `authenticate()`메서드에 `UsernamePasswordAuthenticationToken`을 전달하여 인증을 위임 4. AuthenticationManager- AuthenticationManager는 사용자 인증을 위해 CustomUserDetailsService를 호출5. CustomUserDetailsService - 사용자 로드 요청- CustomUserDetailsService는 UserRepository를 사용하여 사용자 이메일로 데이터베이스에서 사용자 정보를 검색6. UserRepository - findByEmail 호출- UserRepository는 findByEmail(email)메서드를 통해 데이터베이스에서 해당 이메일을 가진 사용자를 조회7. DB 조회 결과 반환- 데이터베이스에서 조회된 User 엔티티가 UserRepository를 통해 반환 |
8. UserPrincipal 생성- 조회된 User 엔티티를 기반으로 UserPrincipal객체가 생성- 이 객체는 Spring Security가 사용자 정보를 관리하는 데 사용 9. UserPrincipal 반환- CustomUserDetailsService는 UserPrincipal을 AuthenticationManager로 반환10. Authentication 성공- AuthenticationManager는 비밀번호 검증을 수행하고 인증 성공 여부를 결정- 성공 시, 인증된 Authentication 객체가 생성 11. JWT 생성- AuthController는 JwtUtil을 호출하여 JWT를 생성- JwtUtil은 사용자 정보를 기반으로 JWT 토큰을 생성 12. AuthResponse 반환- 생성된 JWT를 포함한 AuthResponse가 클라이언트로 반환.13. 클라이언트 응답- 클라이언트는 JWT를 로컬 스토리지나 쿠키에 저장하여 이후 요청에 사용 |
Spring - 인가 과정 (로그인 이후)

1. JWT 추출
2. 사용자 정보 추출
3. 사용자 정보 로드 요청
4. UserRepository 호출
5. 데이터베이스 조회
6. 데이터베이스 조회 결과 반환
7. UserPrincipal 생성
8. UserPrincipal 반환
|
9. JWT 유효성 검증
10. JWT 유효성 결과
11. SecurityContext 설정
12. 컨트롤러로 요청 전달
13. 컨트롤러 응답
14. 클라이언트 응답
|