세션 정책: sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
→ 세션 기반 인증에서는 모든 요청에 세션 생성/유지
<aside>
※ 참고: formLogin().disable()
, httpBasic().disable()
, csrf().disable()
은
본 프로젝트에서 커스텀 로그인 로직을 사용하기 위해 기본 제공 기능을 끈 설정이다.
</aside>
예외 처리:
CustomAuthenticationEntryPoint
(401 예외)CustomAccessDeniedHandler
(403 예외)<aside>
SecurityConfig 전체 코드
https://github.com/melly8954/auth-session/blob/main/src/main/java/com/melly/authsession/config/SecurityConfig.java
</aside>
로그인 요청(/api/v1/auth/login)
서비스 계층(AuthServiceImpl )의 login() 호출
UsernamePasswordAuthenticationToken
을 인증 요청용 토큰 ****생성// AuthServiceImpl.java
UsernamePasswordAuthenticationToken authToken =
new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword());
AuthenticationManager.authenticate()
호출// AuthServiceImpl.java
Authentication authentication = authenticationManager.authenticate(authToken);
AuthenticationManager
가 호출되면 Spring Security 내부에서 등록된 AuthenticationProvider를 찾아 authenticate()
를 호출CustomAuthenticationProvider.authenticate(authToken)
가 실행CustomAuthenticationProvider
에서 사용자 조회, 비밀번호 검증, 계정 상태 체크 수행
→ 인증 성공 시 인증 완료 토큰 반환
<aside>
CustomAuthenticationProvider 전체 코드
https://github.com/melly8954/auth-session/blob/main/src/main/java/com/melly/authsession/common/auth/CustomAuthenticationProvider.java
</aside>
// CustomAuthenticationProvider.java
return new UsernamePasswordAuthenticationToken(principalDetails, null, authorities);
PrincipalDetails
객체 (사용자 정보)null
(보안상 비워둠)CustomAuthenticationProvider
가 반환하는 토큰은 이제 Spring Security에서 인증 완료된 객체를 의미함SecurityContextHolder에 저장
// AuthServiceImpl.java
SecurityContextHolder.getContext().setAuthentication(authentication);
authentication
변수는 이미 CustomAuthenticationProvider
가 반환한 인증 완료 토큰 입니다.AuthenticationManager
로 보내고,SecurityContextHolder
로 인증된 사용자를 참조 가능세션에 SecurityContext 저장
// AuthServiceImpl.java
HttpSession session = httpRequest.getSession(true);
session.setAttribute(
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
SecurityContextHolder.getContext()
);
JSESSIONID
세션 생성 (없으면 새로 생성)JSESSIONID
로 세션이 매핑됨SecurityContextPersistenceFilter
)이 요청 올 때마다 세션에서 SecurityContext
를 꺼내서 SecurityContextHolder
에 복원텍스트 기반 시각화
[사용자] --- 로그인 요청 ---> [AuthController.login()]
|
v
[AuthServiceImpl.login()]
|
v
[AuthenticationManager.authenticate()]
|
v
[CustomAuthenticationProvider]
(사용자 조회 → 비밀번호 검증 → 권한 세팅)
|
v
[Authentication 객체 반환]
|
v
SecurityContextHolder.setAuthentication(auth)
|
v
HttpSession.setAttribute(SPRING_SECURITY_CONTEXT_KEY, auth)
|
v
[사용자에게 JSESSIONID 쿠키 전달]
/oauth2/authorization/{provider}
)