WAS의 경우 새로운 요청이 들어온 경우 큐에 적재되고 쓰레드 풀 내 하나의 쓰레드를 사용하여 처리하게 되는 방식으로 동작하게 된다.
동일한 thread에서 실행되는 동안(하나의 요청을 처리하는 동안) 거치는 Controller, Service, Repository, 도메인 모델 모두에서 접근이 가능한 로컬 변수 기능으로 사용이 완료되면 해당 값을 반드시 remove해야 되고 하지 않게 된다면 이전 요청에 처리된 변수를 읽어 잘못된 동작을 수행할 수 있다.
ThreadLocal<Integer> threadLocalValue = new ThreadLocal<>();
threadLocalValue.set(1);
Integer result = threadLocalValue.get();
//꼭 해야된다!
threadLocal.remove();
SecurityContext 데이터를 쓰거나 읽을수 있는 API를 제공하는데 보안과 관련된 정보를 ThreadLocal를 이용하여 매개변수를 사용한 전달 없이 접근이 가능하다.
final class ThreadLocalSecurityContextHolderStrategy implements SecurityContextHolderStrategy {
private static final ThreadLocal<SecurityContext> contextHolder = new ThreadLocal<>();
@Override
public void clearContext() {
contextHolder.remove();
}
@Override
public SecurityContext getContext() {
SecurityContext ctx = contextHolder.get();
if (ctx == null) {
ctx = createEmptyContext();
contextHolder.set(ctx);
}
return ctx;
}
@Override
public void setContext(SecurityContext context) {
Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
contextHolder.set(context);
}
@Override
public SecurityContext createEmptyContext() {
return new SecurityContextImpl();
}
}
사용자 요청에 대한 인증 객체인 Authentication를 가져오고 등록할 때 사용된다.
public interface SecurityContext extends Serializable {
Authentication getAuthentication();
void setAuthentication(Authentication authentication);
}
사용자를 표현하는 인증 토큰 객체이다.
AnonymousAuthenticationToken
UsernamePasswordAuthenticationToken
RememberMeAuthenticationToken