저번 글에서 SessionManagement 에 대해서 소개하는 글을 적었습니다. 공식문서에 있는 글을 최대한 줄이고 압축해서 글을 쓰려다보니 설명이 부족한 부분도 많았던 것 같습니다. 그래서 두 파트로 나누었고 이번 글에서는 SessionManagement를 어떤식으로 적용하는지 보여드리도록 하겠습니다.
1. 동시 로그인 차단하기
먼저 동시 세션을 제어해서 하나의 로그인한 허용해보도록 하겠습니다.
저는 최대 1개의 세션만 허용하고 새로운 로그인이 발생하면 이전 세션을 만료시키겠습니다. 그리고 세션이 만료가 되면 "/join?expired" 로 이동시키도록 제어해 보겠습니다.
UserDetails
세션을 1개로 제한한다는 것은 이전 세션과 비교해서 같은세션인지 확인하는 과정이 있어야 가능합니다. 이전 시간에 UserDetails를 구현한 PrincipalDetails 구현체가 있었습니다. 이 PrincipalDetails 의 equals와 hashCode를 override하겠습니다.
여기서 한가지 알아야할 것은 PrincipalDetails 객체 자체를 비교하는것은 중요하지 않습니다. 그 안에 있는 User를 비교하는 것이 더 중요합니다. User의 기본키는 교유하기 때문입니다.
먼저 User 객체의 equals와 hashCode를 override 하겠습니다.
@Getter @Setter
@EqualsAndHashCode(of = "username")
public class User {
private String username;
private String password;
private String role;
private String name;
}
저는 간단한 개발환경을 위해서 기본키값을 username으로 했지만 실제 DB를 사용하는 환경에서는 id값을 비교하면됩니다.
lombok을 사용하지 않을 경우
@Getter @Setter
public class User {
private String username;
private String password;
private String role;
private String name;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(username, user.name);
}
@Override
public int hashCode() {
return Objects.hash(username, username);
}
}
JPA가 기본적으로 id 기반으로 equals/hashCode 제공합니다. 복합키를 사용하거나 또는 명확성을 위해서 객체에서 override해주는 것도 좋은 방법이라고 생각합니다.
public record PrincipalDetails(User user) implements UserDetails {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of(new SimpleGrantedAuthority(user.getRole()));
}
@Override
public String getPassword() {
return user == null ? null : user.getPassword();
}
@Override
public String getUsername() {
return user == null ? null : user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
Spring Security의 세션 관리는 사용자의 세션을 생성, 유지, 파괴하는 전반적인 프로세스를 관리합니다. 이는 보안과 사용자 경험 모두에 중요한 영향을 미칩니다. 또한 JWT이나 Session 관리를 하지않는 API를 사용하기전에 알아두어야 하기때문에 공부해보도록 하겠습니다.
2. Session Creation Policy (세션 생성 정책)
http.sessionManagement(sessionManagement -> sessionManagement
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) // 필요한 경우에만 생성(Default)
);
정책
설명
SessionCreationPolicy.ALWAYS
항상 세션 생성
SessionCreationPolicy.IF_REQUIRED
필요한 경우에만 생성 (Default)
SessionCreationPolicy.NEVER
생성하지 않지만 존재하면 사용
SessionCreationPolicy.STATELESS
세션을 완전히 사용하지 않음 (JWT 등의 토큰 기반 인증에 적합)
3. Concurrent Session Control (동시 세션 제어)
@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
http.sessionManagement(sessionManagement -> sessionManagement
.maximumSessions(1) // 사용자당 최대 세션 수
.maxSessionsPreventsLogin(true) // true: 새로운 로그인 차단, false: 기존 세션 만료(기본값)
.expiredUrl("/session-expired") // 세션 만료시 이동할 URL
);
3-1. HttpSessionEventPublisher
HttpSessionEventPublisher는 세션 생명주기 이벤트를 Spring의 ApplicationContext에 발행하는 역할을 합니다.
@Component
public class SessionEventListener {
private final Logger logger = LoggerFactory.getLogger(getClass());
@EventListener
public void handleSessionCreated(HttpSessionCreatedEvent event) {
HttpSession session = event.getSession();
logger.info("새 세션 생성: {}", session.getId());
}
@EventListener
public void handleSessionDestroyed(HttpSessionDestroyedEvent event) {
HttpSession session = event.getSession();
logger.info("세션 파괴됨: {}", session.getId());
}
}
세션 모니터링
@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
@Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
http.sessionManagement(session -> session
.sessionRegistry(sessionRegistry())
);
@Component
@Slf4j
@RequiredArgsConstructor
public class SessionEventListener {
private final SessionRegistry sessionRegistry;
@EventListener
public void handleSessionDestroyed(HttpSessionDestroyedEvent event) {
log.info("세션만료 : {}", event.getSession().getId());
// 세션이 만료되면 해당 사용자의 세션 정보 정리
SecurityContext securityContext = (SecurityContext) event.getSession()
.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
if (securityContext != null) {
sessionRegistry.removeSessionInformation(event.getSession().getId());
}
}
@EventListener
public void handleSessionCreated(HttpSessionCreatedEvent event) {
log.info("세션생성 : {}", event.getSession().getId());
HttpSession session = event.getSession();
// 세션 생성 시 기본 타임아웃 설정
session.setMaxInactiveInterval(60 * 30); // 30분
}
}
정확히는 세션 고정 공격 보호 (Session Fixation Attack Protection) 입니다. 세션 고정 공격은 악의적인 공격자가 사이트에 접속해서 세션을 생성한 다음 동일한 세션으로 다른 사용자가 접속하도록 유도할 수 있는 잠재적인 공격입니다. (예, 세션 식별자를 매개변수로 포함하는 링크를 전송) Spring Security는 사용자가 로그인할 때 새 세션을 생성하거나 세션 ID를 변경하여 이를 자동으로 보호하는데 이를 설정하는 것이 sessionFixation 설정입니다.
세션은 자체적으로 만료되며 Security Context가 제거되도록 해야할 것은 없습니다. 그러므로 세션이 만료된 시점을 감지하고 사용자가 특정 작업을 수행할 수 있도록 엔드포인트를 리디렉션할 수 있게만 해주면됩니다. 이는 invalidSessionUrl 에서 이루어집니다.
http.sessionManagement(session -> session
.invalidSessionUrl("/invalidSession") // 만료된 세선이 접근할 경우 "/invalidSession" 으로 이동
);
http.sessionManagement(session -> session
.invalidSessionStrategy(new CustomInvalidSessionStrategy())
);
public class CustomInvalidSessionStrategy implements InvalidSessionStrategy {
@Override
public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Session 무효화
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
// JSESSIONID 쿠키 삭제
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("JSESSIONID".equals(cookie.getName())) {
cookie.setValue("");
cookie.setPath("/");
cookie.setMaxAge(0);
response.addCookie(cookie);
break;
}
}
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<script>alert('세션이 만료되었습니다.');</script>");
out.flush();
}
}
invalidSessionUrl과 invalidSessionStrategy는 동시에 사용할 수 없습니다. 둘다 정의 되어있다면 invalidSessionStrategy만 적용됩니다. 그냥 세션 만료시 이동을 원할경우 invalidSessionUrl을 사용하고, 복잡한 로직이 추가되어야 한다면 invalidSessionStrategy를 사용하시면 됩니다.
주의사항
로그아웃 시에 쿠키가 제대로 삭제되지 않아 문제가 발생할 수 있습니다.
http.logout(logout -> logout
// 모든 쿠키 제거
.addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(ClearSiteDataHeaderWriter.Directive.COOKIES)))
// 특정 쿠키 제거
.deleteCookies("JSESSIONID", "remember-me")
);
이렇게 명시적으로 쿠키를 제거해줍시다.
ClearSiteData를 지원하지 않는 브라우저에서는 정상적으로 동작하지 않을 수 있습니다.
6. SessionManagementFilter
sessionManagement는 SessionManagementFilter에서 사용됩니다. 그 역할로는
세션 생성 전략 관리
동시 세션 제어
세션 고정 보호
유효하지 않은 세션 처리
우리가 위에서 알아본 것과 같습니다.
6-1. SessionManagementFilter 구조
SecurityContextRepository의 내용을 현재 SecurityContextHolder의 내용과 비교 검사
이를 통해 현재 요청 중에 사용자가 인증되었는지 확인
주로 pre-authentication이나 remember-me와 같은 비대화형 인증 메커니즘에서 사용됨
처리 흐름
SecurityContextRepository에 Security Context가 있다면 아무 작업도 하지 않음
SecurityContextRepository에 context가 없고, SecurityContext가 Authentication 객체를 포함하고 있다면 (익명객체가 아닌)
이전 필터에서 이미 인증되었다고 가정
설정된 SessionAuthenticationStrategy를 실행
미인증 사용자 처리
유효하지 않은 세션 ID가 요청되었는지 확인 (예: 타임아웃으로 인한 유효하지 않은 세션)
설정된 InvalidSessionStrategy가 있다면 이를 실행
6-2. SecurityContextRepository
SecurityContextRepository는 SecurityContext를 저장하고 불러오는 역할을 하는 인터페이스입니다. 주로 HTTP 세션에 SecurityContext를 저장하고 검색하는 작업을 담당합니다. 기본객체는 HttpSessionSecurityContextRepository 입니다.
기본 구현
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.securityContext((securityContext) -> securityContext
.securityContextRepository(new HttpSessionSecurityContextRepository())
);
return http.build();
}
}
DelegatingSecurityContextRepository 사용 시
@Bean
public SecurityContextRepository securityContextRepository() {
return new DelegatingSecurityContextRepository(
new HttpSessionSecurityContextRepository(),
new RequestAttributeSecurityContextRepository()
);
}
# 쿠키 만료 시간 설정
server.servlet.session.timeout=30m
# 쿠키 경로 설정
server.servlet.session.cookie.path=/
# 쿠키 도메인 설정
server.servlet.session.cookie.domain=example.com
# 쿠키 이름 변경
server.servlet.session.cookie.name=MYSESSIONID
# SameSite 설정
server.servlet.session.cookie.same-site=strict
글이 너무 길어져서 여기까지 작성하겠습니다.
SessionManagement 관련된 내용은 어마어마하게 많습니다. 다음글에서는 이 글을 토대로 어떻게 적용하는지에 대해서 알아보도록하겠습니다.
CORS(Cross-Origin Resource Sharing)는 웹 브라우저에서 외부 도메인 리소스를 안전하게 요청할 수 있도록 하는 표준 규약입니다. 프론트엔드와 백엔드가 분리하는데 있어 CORS에 대해서 반드시 짚고 넘어가야합니다. 그래서 온르은 CORS에 대해서 공부해보겠습니다.
2. CORS의 필요성
핵심은 외부로부터 리소스를 공유하는 것입니다. 요즘 웹 애플리케이션에 개발에서 백엔드와 프론트엔드를 구분하지 않고 개발하는 곳은 거의 없을 겁니다.
프론트엔드와 백엔드의 분리
마이크로서비스 아키텍처 도입
외부 API 활용
SPA(Single Page Application) 개발 방식
이러한 상황에서 다른 출처(Origin)의 리소스를 안전하게 요청하고 사용할 수 있어야 했고, 이를 위한 표준이 바로 CORS입니다.
3. Same-Origin Policy
Same-Origin Policy는 웹 브라우저의 기본적인 보안 정책으로, 같은 출처에서만 리소스를 공유할 수 있도록 제한합니다.
출처(Origin)는 다음 세 가지 요소로 결정됩니다:
프로토콜 (http, https)
호스트 (domain)
포트 번호
http://example.com/path1, https://example.com/path2 는 프로토콜이 다르므로 다른 출처로 간주됩니다.
4. CORS 동작 방식
CORS는 HTTP 헤더를 통해 동작합니다. 주요 헤더는 다음과 같습니다:
4-1. 요청 헤더
Origin: 요청을 보내는 출처
Access-Control-Request-Method: 실제 요청에서 사용할 HTTP 메서드
Access-Control-Request-Headers: 실제 요청에서 사용할 헤더
4-2. 응답 헤더
Access-Control-Allow-Origin: 허용된 출처
Access-Control-Allow-Methods: 허용된 HTTP 메서드
Access-Control-Allow-Headers: 허용된 헤더
Access-Control-Max-Age: 프리플라이트 요청 캐시 시간
Access-Control-Allow-Credentials: 인증 정보 포함 여부
5. CORS 요청의 종류
5-1. Simple Request
GET, HEAD, POST 중 하나의 메서드 사용
허용된 헤더만 사용
Content-Type이 다음 중 하나:
application/x-www-form-urlencoded
multipart/form-data
text/plain
5-2. Preflight Request
Simple Request 조건을 만족하지 않는 요청의 경우, 브라우저는 실제 요청 전에 OPTIONS 메서드를 사용한 예비 요청을 보냅니다.
5-3. Credentialed Request
인증 정보(쿠키, HTTP 인증)를 포함한 요청입니다.
6. Spring Security CORS 설정
Spring Security CORS 설정에 대해서 알아보겠습니다.
UrlBasedCorsConfigurationSource apiConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
// 허용할 출처(Origin) 설정
// https://api.example.com 에서 오는 요청만 허용
configuration.setAllowedOrigins(List.of("https://api.example.com"));
configuration.setAllowedOriginPatterns(List.of(
"https://*.example.com", // example.com의 모든 서브도메인 허용
"https://*.example.*.com", // 더 복잡한 패턴 매칭도 가능
"http://localhost:[*]" // 로컬호스트의 모든 포트 허용
));
// 허용할 HTTP 메서드 설정
// GET과 POST 메서드만 허용 (PUT, DELETE, PATCH 등은 차단됨)
configuration.setAllowedMethods(List.of("GET","POST"));
// 허용할 헤더 설정
// 모두 허용
configuration.setAllowedHeaders(List.of("*"));
// 클라이언트에게 노출할 헤더
configuration.setExposedHeaders(List.of("Authorization"));
// allowCredentials를 true로 설정할 경우, allowedOrigins에 "*"를 사용할 수 없습니다
configuration.setAllowCredentials(true);
// CORS 프리플라이트 요청의 캐시 시간
configuration.setMaxAge(3600L);
// URL 패턴별로 CORS 설정을 적용할 수 있는 객체 생성
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 모든 경로("/**")에 대해 위에서 설정한 CORS 설정을 적용
source.registerCorsConfiguration("/**", configuration);
return source;
}
따라서 브라우저는 이러한 보안 위험을 방지하기 위해 allowCredentials(true)와 allowedOrigins("*")의 조합을 명시적으로 금지하고 있습니다. 이는 웹 보안의 기본 원칙인 "최소 권한의 원칙"을 따르는 것이며, 실수로 인한 보안 취약점 발생을 방지합니다.
7. 자주 발생하는 CORS 에러와 해결 방법
7-1. No 'Access-Control-Allow-Origin' header is present
원인: 서버에서 Access-Control-Allow-Origin 헤더를 설정하지 않음
해결: 서버에서 적절한 CORS 설정 추가
7-2. Method not allowed
원인: 허용되지 않은 HTTP 메서드 사용
해결: allowedMethods에 필요한 메서드 추가
7-3. Credentials flag is true, but Access-Control-Allow-Credentials is false
원인: 인증 정보를 포함한 요청에 대한 서버 설정 미비
해결: allowCredentials(true) 설정 추가
8. 보안 관련 고려사항
8-1. Origin 설정
"*" 대신 구체적인 도메인 지정
신뢰할 수 있는 출처만 허용
8-2. 인증 관련
allowCredentials(true) 사용 시 구체적인 출처 지정 필요
보안에 민감한 API의 경우 더 엄격한 CORS 정책 적용
8-3. 헤더 설정
필요한 헤더만 허용
exposedHeaders 설정 시 최소한의 헤더만 노출
8-4. 캐시 설정
maxAge 값을 적절히 설정하여 불필요한 프리플라이트 요청 감소
9. 결론
CORS는 현대 웹 개발에서 필수적인 보안 메커니즘입니다. 올바른 CORS 설정은 웹 애플리케이션의 보안과 기능성을 모두 만족시킬 수 있습니다. 각 프로젝트의 요구사항과 보안 정책에 맞게 적절한 CORS 설정을 적용하시기 바랍니다.
Spring Security의 Anonymous 인증은 인증되지 않은 사용자(로그인하지 않은 사용자)를 처리하는 메커니즘입니다. 인증되지 않은 요청에 대해 AnonymousAuthenticationToken을 생성하여 보안 컨텍스트에 저장합니다. 내용을 길지않으니 빠르게 알아보겠습니다.
사용법
anonymous 설정은 아래와 같습니다.
http.anonymous(anonymous -> anonymous
.principal("anonymousUser") // 익명 사용자의 주체
.authorities("ROLE_ANONYMOUS") // 익명 사용자의 권한
);
// 비활성화
http.anonymous(AbstractHttpConfigurer::disable);
if (auth instanceof AnonymousAuthenticationToken) {
// 익명 사용자
} else {
// 실제 인증된 사용자
}
이렇게 사용하셔야합니다.
ExceptionHandling
http.exceptionHandling(handling -> handling
.accessDeniedHandler() // 권한 부족 시 처리
.accessDeniedPage() // 권한 부족 시 리다이렉트할 페이지
.authenticationEntryPoint() // 인증되지 않은 사용자 처리
.defaultAuthenticationEntryPointFor() // 특정 요청에 대한 인증 진입점 설정
);
accessDeniedHandler
.accessDeniedHandler((request, response, accessDeniedException) -> {
// 인증된 사용자가 권한이 부족한 리소스에 접근할 때
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<script>alert('권한이 없습니다.'); window.location.href='/';</script>");
out.flush();
})
accessDeniedPage
.accessDeniedPage("/error/403") // 간단히 특정 페이지로 리다이렉트
authenticationEntryPoint
.authenticationEntryPoint((request, response, authException) -> {
// 인증되지 않은 사용자가 보호된 리소스에 접근할 때
response.sendRedirect("/login");
})
defaultAuthenticationEntryPointFor
.defaultAuthenticationEntryPointFor(
new LoginUrlAuthenticationEntryPoint("/api/login"),
new AntPathRequestMatcher("/api/**")
)
전체 코드
http.exceptionHandling(handling -> handling
// 1. 권한 부족 처리 (403)
.accessDeniedHandler((request, response, accessDeniedException) -> {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<script>alert('권한이 없습니다.'); history.back();</script>");
out.flush();
})
// 2. 인증되지 않은 사용자 처리 (401)
.authenticationEntryPoint((request, response, authException) -> {
if (isAjaxRequest(request)) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
} else {
response.sendRedirect("/login");
}
})
// 3. API 요청에 대한 특별한 처리
.defaultAuthenticationEntryPointFor(
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
new AntPathRequestMatcher("/api/**")
)
);
// AJAX 요청 확인
private boolean isAjaxRequest(HttpServletRequest request) {
return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}
Spring Security 에서 ThreadLocal에대해서 언급한적이 있어 글로 남겨봅니다.
ThreadLocal이란?
ThreadLocal은 Java에서 제공하는 클래스로, java.lang 패키지에 존재합니다.
각 스레드마다 독립적인 변수를 가질 수 있게 해주는 기능인데 쉽게 말해, ThreadLocal에 저장된 데이터는 해당 Thread만 접근할 수 있는 데이터 저장소라고 할 수 있습니다. 개인이 가지는 사물함이라고 생각하시면 쉽습니다.
동시성 문제
그럼 왜 ThreadLocal을 알아야 할까요? JAVA는 멀티쓰레딩 환경으로 한 메소드에 동시에 접근이 가능합니다. 그래서 항상 동시성문제에 신경써야하죠. 특히 Spring Container에서는 Bean으로 등록해 객체를 싱글톤으로 관리해 자원을 최소화 합니다. 하나의 객체를 여러명이 사용하면 문제가 생기기 마련입니다. 읽기 메소드는 멱등성을 보장받아 문제가 생기지않지만 수정, 생성, 삭제 등 데이터가 변경되었을 때 문제가 생기죠.
public class BankAccount {
private int balance = 0;
// 동시성 문제가 발생하는 메서드
public int transfer(int amount) {
int currentBalance = balance; // 현재 잔액 읽기
balance = currentBalance + amount; // 잔액 업데이트
return balance;
}
public int getBalance() {
return balance;
}
}
가령 BankAccount 객체가 싱글톤으로 관리되고, 여러 사용자가 BankAccount를 사용한다고 했을때,
사용자A : bankAccount.transfer(1000)
사용자A 현재 잔액 읽음 : 현재 잔액 0
사용자B : bankAccount.transfer(1000)
사용자B 현재 잔액 읽음 : 현재 잔액 0
사용자A : 잔액 업데이트 - 결과 반환 1000
사용자B : 잔액 업데이트 - 결과 반환 1000
최종 잔액이 2000이 될 것으로 예상했지만 동시성 문제로 최종 잔액이 1000이 되었습니다.
ThreadLocal의 특징
스레드 안전성: 각 스레드가 자신만의 독립된 변수를 가지므로, 동기화 없이도 스레드 안전성을 보장합니다.
데이터 격리: 다른 스레드의 데이터에 접근할 수 없어 데이터 격리가 완벽하게 이루어집니다.
성능: 동기화가 필요 없으므로, synchronized 키워드 사용 대비 성능상 이점이 있습니다.
ThreadLocal
public class ThreadLocal<T> {
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
boolean isPresent() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
return map != null && map.getEntry(this) != null;
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
map.set(this, value);
} else {
createMap(t, value);
}
}
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null) {
m.remove(this);
}
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
static class ThreadLocalMap {
static class Entry extends WeakReference<java.lang.ThreadLocal<?>> {
Object value;
Entry(java.lang.ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
}
}
ThreadLocal은 ThreadLocalMap을 가지고있고 여기에서 key, value로 데이터를 보관합니다.
그리고 이때 get()메소드에서 Thread.currentThread()를 사용해 Thread를 꺼내고 그 ThreadLocalMap을 반환해서 가져오게됩니다.
이제 개념을 알았으니 어디에서 사용하고 있는지 간단하게 알아보겠습니다.
사용 사례
Spring Security
public class SecurityContextHolder {
// ... 코드 생략
private static void initializeStrategy() {
if ("MODE_PRE_INITIALIZED".equals(strategyName)) {
Assert.state(strategy != null, "When using MODE_PRE_INITIALIZED, setContextHolderStrategy must be called with the fully constructed strategy");
} else {
if (!StringUtils.hasText(strategyName)) {
strategyName = "MODE_THREADLOCAL"; // ThreadLocal 전략이 Default
}
if (strategyName.equals("MODE_THREADLOCAL")) {
strategy = new ThreadLocalSecurityContextHolderStrategy();
} else if (strategyName.equals("MODE_INHERITABLETHREADLOCAL")) {
strategy = new InheritableThreadLocalSecurityContextHolderStrategy();
} else if (strategyName.equals("MODE_GLOBAL")) {
strategy = new GlobalSecurityContextHolderStrategy();
} else {
try {
Class<?> clazz = Class.forName(strategyName);
Constructor<?> customStrategy = clazz.getConstructor();
strategy = (SecurityContextHolderStrategy)customStrategy.newInstance();
} catch (Exception ex) {
ReflectionUtils.handleReflectionException(ex);
}
}
}
}
final class ThreadLocalSecurityContextHolderStrategy implements SecurityContextHolderStrategy {
private static final ThreadLocal<Supplier<SecurityContext>> contextHolder = new ThreadLocal();
// ... 코드 생략
}
Transaction
public class DataSourceTransactionManager extends AbstractPlatformTransactionManager implements ResourceTransactionManager, InitializingBean {
// ... 코드 생략
protected Object doGetTransaction() {
DataSourceTransactionObject txObject = new DataSourceTransactionObject();
txObject.setSavepointAllowed(this.isNestedTransactionAllowed());
ConnectionHolder conHolder = (ConnectionHolder)TransactionSynchronizationManager.getResource(this.obtainDataSource());
txObject.setConnectionHolder(conHolder, false);
return txObject;
}
protected void doBegin(Object transaction, TransactionDefinition definition) {
// ... 코드 생략
if (txObject.isNewConnectionHolder()) {
TransactionSynchronizationManager.bindResource(this.obtainDataSource(), txObject.getConnectionHolder());
}
// ... 코드 생략
}
}
public abstract class TransactionSynchronizationManager {
private static final ThreadLocal<Map<Object, Object>> resources = new NamedThreadLocal("Transactional resources");
private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations = new NamedThreadLocal("Transaction synchronizations");
private static final ThreadLocal<String> currentTransactionName = new NamedThreadLocal("Current transaction name");
private static final ThreadLocal<Boolean> currentTransactionReadOnly = new NamedThreadLocal("Current transaction read-only status");
private static final ThreadLocal<Integer> currentTransactionIsolationLevel = new NamedThreadLocal("Current transaction isolation level");
private static final ThreadLocal<Boolean> actualTransactionActive = new NamedThreadLocal("Actual transaction active");
// ... 코드 생략
}
Hibernate
public class ThreadLocalSessionContext extends AbstractCurrentSessionContext {
private static final CoreMessageLogger LOG = (CoreMessageLogger)Logger.getMessageLogger(CoreMessageLogger.class, ThreadLocalSessionContext.class.getName());
private static final Class<?>[] SESSION_PROXY_INTERFACES = new Class[]{Session.class, SessionImplementor.class, EventSource.class, LobCreationContext.class};
private static final ThreadLocal<Map<SessionFactory, Session>> CONTEXT_TL = ThreadLocal.withInitial(HashMap::new);
// ... 코드 생략
}
ThreadLocal 주의사항
메모리 누수
ThreadLocal 사용 후에는 반드시 remove()를 호출하여 메모리 누수를 방지해야 합니다. 특히 스레드 풀을 사용하는 환경에서는 더욱 중요합니다.
try {
// ThreadLocal 사용
userContext.set(new UserContext());
// 비즈니스 로직
} finally {
// 반드시 삭제
userContext.remove();
}
가능하면 try-with-resources 패턴을 사용해 자원을 반납하면 안전하게 사용할 수 있습니다.
성능 고려사항
ThreadLocal은 각 스레드마다 별도의 메모리를 사용합니다.
많은 수의 ThreadLocal 변수를 사용하면 메모리 사용량이 증가할 수 있습니다.
get()과 set() 연산은 매우 빠르지만, 너무 빈번한 접근은 피하는 것이 좋습니다.
static final 선언
static final로 선언하는걸 권장합니다. 위에 사용 사례를 보시면 모두 static final로 선언되어있는걸 보실 수 있습니다.
@Getter @Setter
@ToString
public class User {
private String username;
private String password;
private String role;
private String name;
}
User에는 아이디, 비밀번호, 권한, 이름을 저장합니다.
MainController
@Controller
public class MainController {
@GetMapping
public String mainPage() {
return "index";
}
@GetMapping("/user")
public String userPage(@SessionAttribute("user") String username, Model model) {
model.addAttribute("user", username);
return "userForm";
}
@GetMapping("/join")
public String loginPage() {
return "joinForm";
}
@GetMapping("/signup")
public String signupPage() {
return "signupForm";
}
}
HTML과 매핑해줍니다.
UserController
@Controller
@RequiredArgsConstructor
public class UserController {
private final MemoryDB db;
private final BCryptPasswordEncoder encoder;
@PostMapping("/signup")
public String signup(User user) {
user.setRole("ROLE_USER");
db.save(user);
return "redirect:/join";
}
@PostMapping("/join")
public String login(HttpServletRequest request, User user) {
User findUser = db.find(user.getUsername());
if (findUser == null || !encoder.matches(user.getPassword(), findUser.getPassword())) {
return "redirect:/join";
}
request.getSession().setAttribute("user", findUser.getUsername());
return "redirect:/user";
}
}
로그인과 회원가입 POST 요청을 처리합니다.
DB
@Component
@RequiredArgsConstructor
public class MemoryDB {
private final Map<String, User> db = new HashMap<>();
private final BCryptPasswordEncoder encoder;
public User save(User user) {
user.setPassword(encoder.encode(user.getPassword()));
db.put(user.getUsername(), user);
return user;
}
public User find(String username) {
return db.get(username);
}
}
DB에 유저정보를 저장하고 간단한 예제 구현을 위해 Key값을 아이디로 잡았습니다.
Config
@Bean
BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
비밀번호는 암호화를 위해 BCryptPasswordEncode를 사용했습니다.
이렇게 하면 잘 동작할겁니다. 실제로는 예외처리등 수 많은 로직이 존재할겁니다. 이걸 Spring Security에게 위임해보겠습니다.
Security LoginForm 적용 후
먼저 UserController에서 우리가 로그인을 직접 구현했던 @PostMapping("/join") 부분을 제거해줍니다.
@Controller
@RequiredArgsConstructor
public class UserController {
private final MemoryDB db;
private final BCryptPasswordEncoder encoder;
@PostMapping("/signup")
public String signup(User user) {
user.setRole("ROLE_USER");
db.save(user);
return "redirect:/join";
}
}
@RequiredArgsConstructor
public class PrincipalDetails implements UserDetails {
private final User user;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of(new SimpleGrantedAuthority(user.getRole()));
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
UserDetails 를 구현해줍니다. 여기에 우리가 구현한 User를 멤버변수로 받고 getUsername과 getPassword를 이어줍니다.
나머지는 일단 true로 둡시다.
@Service
@RequiredArgsConstructor
public class PrincipalDetailsService implements UserDetailsService {
private final MemoryDB db;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User findUser = db.find(username);
if (findUser == null) {
throw new UsernameNotFoundException("아이디 또는 비밀번호가 일치하지 않습니다.");
}
return new PrincipalDetails(findUser);
}
}
UserDetailsService를 구현하고 DB와 연동해줍니다. loadUserByUsername의 반환값은 위에서 구현한 PrincipalDetails로 해주고 User 객체를 넣어줍니다.
이 권한 PrincipalDetails에 getAuthorities() 에 구현한 데이터를 기반으로 동작합니다. 그런데 우리는 "ROLE_USER" 를 넣었지 "USER"를 넣지는 않았습니다. 그 이유는 GrantedAuthority 기본 규칙은 "ROLE_" 접두사를 사용하는것이 default 이기 때문입니다.
특정 URL 패턴에 대한 접근 설정 requestMatchers("/user/**") : /user 하위 URL에 대한 접근 설정 requestMatchers(HttpMethod.GET, "/user"/**") : /user 하위 URL에 GET 접근에 대한 설정 requestMatchers(HttpMethod.GET) : GET 접근에 대한 설정
authenticated()
인증된 사용자만 접근 허용
permitAll()
모든 사용자 접근 허용
denyAll()
모든 접근 거부
hasAuthority(String authority)
특정 권한을 가진 사용자만 접근 hasAuthority("USER") -> "USER" 접근
hasAnyAuthority(String... authorities)
여러 권한 중 하나라도 가진 사용자만 접근
hasRole(String role)
특정 권한을 가진 사용자만 접근 (ROLE_ 접두사 자동 추가) hasRole("USER") -> "ROLE_USER" 에 접근
hasAnyRole(String... roles)
여러 역할 중 하나라도 가진 사용자 접근 (ROLE_ 접두사 자동 추가)
결과
로그인이 되어있지 않은 유저가 /user 로 접근하는 경우 /join 으로 redirect되어 로그인이 진행된 후에 /user 접근이 됩니다.
CSRF Cross-Site Request Forgery의 약자로 인증된 사용자의 권한을 악용하여 해당 사용자가 의도하지 않은 요청을 웹사이트에 전송하는 공격 기법입니다. 공격자는 사용자가 이미 인증된 상태를 악용하여 사용자의 의도와는 무관한 작업을 수행하게 만듭니다. 다시 말해 인증된 요청과 위조된 요청을 구분하지 못하고 서버에서 요청을 처리하여 문제가 생기는 것을 말하는데요. 웹 개발자라면 반드시 알아야하는 부분입니다. 오늘은 이것에 대해서 알아보도록 하겠습니다.
CSRF 공격
CSRF 공격에 대해서 예시와 함께 알아보도록하겠습니다.
예시로 은행 웹사이트에서 로그인한 사용자로부터 돈을 이체할 수 있는 Form이 있다고 가정하겠습니다.
위조된 웹사이트에서 submit을 하면 공격자 계좌로 송금이 될겁니다. 이는 위조된 웹사이트가 사용자의 쿠키를 볼 수 없지만 은행과 관련된 쿠키는 여전히 남아 요청과 함께 전송되기 때문에 발생합니다. 더욱 큰 문제는 버튼을 클릭해 submit 하지 않아도 JavaScript를 사용하여 자동화하여 제출할 수 있다는 것입니다. 그렇다면 어떻게 이 문제를 해결할 수 있을까요?
// 잘못된 예시 - GET으로 데이터 변경
@GetMapping("/user/delete/{id}") // ❌ 절대 하면 안 됨
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
// 올바른 예시 - POST로 데이터 변경
@PostMapping("/user/delete/{id}") // ✅ 올바른 방법
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
1. Synchrozier Token Pattern
form 안에 CSRF 토큰을 넣어주는겁니다. 그러면 서버는 토큰을 조회하여 값이 일치하지 않으면 요청을 거부할 수 있게됩니다. 핵심은 쿠키는 브라우저에서 자동으로 HTTP 요청에 포함되지만 CSRF 토큰이 브라우저에서 자동으로 포함되지 않는다는 것입니다.
http.csrf(csrf -> {
csrf
// CSRF 완전 비활성화
.disable()
// 특정 경로 CSRF 검증 제외
.ignoringAntMatchers("/api/**")
// RequestMatcher로 더 복잡한 조건으로 제외할 경로 설정
.ignoringRequestMatchers(requestMatcher)
// CSRF 토큰 저장소 설정
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
// 커스텀 CSRF 토큰 저장소 설정
.csrfTokenRepository(new CustomCsrfTokenRepository())
// CSRF 토큰 생성 요청 처리 경로 설정 (기본값: "_csrf")
.csrfTokenRequestHandler(requestHandler)
// 세션 속성 이름 설정 (기본값: "CSRF_TOKEN")
.sessionAuthenticationStrategy(sessionAuthenticationStrategy)
// CSRF 토큰 필터 이전에 실행될 필터 추가
.requireCsrfProtectionMatcher(requestMatcher)
});
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) 는 JavaScript에서 CSRF 토큰을 사용 할 수 있도록 쿠키에 저장하는 것인데, 위에서 설명했듯이 API는 csrf.disabled() 해서 사용하는 것이 더 유용할 수 있습니다.
결론
CSRF 공격은 웹 애플리케이션의 중요한 보안 위협이지만, 적절한 방어 메커니즘을 구현함으로써 효과적으로 방어할 수 있습니다. 특히 CSRF 토큰, SameSite 쿠키 설정, 그리고 적절한 헤더 검증을 조합하여 사용하는 것이 권장됩니다.