Spring Security ‐ Session Management - taeyun-ham/andalos GitHub Wiki
Authentication Persistence and Session Management
인증 요청을 처리하는 애플리케이션이 있게 되면, 해당 인증이 향후 요청에서 어떻게 유지되고 복원될지 고려하는 것이 중요합니다.
이것은 기본적으로 자동으로 이루어지므로 추가 코드가 필요하지 않지만, HttpSecurity에서 requireExplicitSave가 의미하는 바를 아는 것이 중요합니다.
원한다면, requireExplicitSave가 수행하는 작업이나 그 중요성에 대해 자세히 알아볼 수 있습니다. 그렇지 않으면 대부분의 경우 이 섹션을 완료했습니다.
그러나 떠나기 전에, 다음 사용 사례 중 어느 것이 귀하의 애플리케이션에 적합한지 고려해 보십시오:
- 세션 관리의 구성 요소를 이해하고 싶습니다.
- 동시에 로그인할 수 있는 사용자 수를 제한하고 싶습니다.
- 스프링 시큐리티가 대신 처리하는 것이 아니라 직접 인증을 저장하고 싶습니다.
- 수동으로 인증을 저장하고 있으며 이를 제거하고 싶습니다.
- SessionManagementFilter를 사용하고 있으며 그것으로부터 벗어나는 데 도움이 필요합니다.
- 세션 외의 다른 것에 인증을 저장하고 싶습니다.
- 상태가 없는(stateless) 인증을 사용하고 있지만 여전히 세션에 저장하고 싶습니다.
- SessionCreationPolicy.NEVER를 사용하고 있지만 애플리케이션이 여전히 세션을 생성하고 있습니다.
Session Management의 구성 요소 이해하기
Session Management 지원은 함께 작동하여 기능을 제공하는 몇 가지 구성 요소로 구성됩니다. 그 구성 요소들은 SecurityContextHolderFilter, SecurityContextPersistenceFilter 및 SessionManagementFilter입니다.
스프링 시큐리티 6에서는 SecurityContextPersistenceFilter와 SessionManagementFilter가 기본적으로 설정되어 있지 않습니다. 더불어, 모든 애플리케이션은 SecurityContextHolderFilter 또는 SecurityContextPersistenceFilter 중 하나만 설정해야 하며, 둘 다 설정해서는 안 됩니다.
SessionManagementFilter
SessionManagementFilter는 현재 SecurityContextHolder의 내용과 SecurityContextRepository의 내용을 비교하여 현재 요청 중에 사용자가 인증되었는지를 결정합니다. 이는 일반적으로 사전 인증(pre-authentication) 또는 리멤버-미(remember-me)와 같은 비대화형 인증 메커니즘을 통해 이루어집니다. 저장소에 보안 컨텍스트가 포함되어 있으면 필터는 아무 것도 하지 않습니다. 그렇지 않고 스레드-로컬 SecurityContext에 (익명이 아닌) Authentication 객체가 포함되어 있다면, 필터는 이전 필터 스택에서 인증이 이루어졌다고 가정합니다. 그러면 구성된 SessionAuthenticationStrategy를 호출합니다.
사용자가 현재 인증되지 않은 경우, 필터는 유효하지 않은 세션 ID(예: 타임아웃으로 인해)가 요청되었는지 확인하고, 설정된 경우 구성된 InvalidSessionStrategy를 호출합니다. 가장 일반적인 행동은 단순히 고정 URL로 리다이렉션하는 것이며, 이는 표준 구현인 SimpleRedirectInvalidSessionStrategy에 의해 캡슐화됩니다. 후자는 앞서 설명한 바와 같이 네임스페이스를 통해 유효하지 않은 세션 URL을 구성할 때도 사용됩니다.
SessionManagementFilter 벗어나기
스프링 시큐리티 5에서는 기본 구성이 SessionManagementFilter에 의존하여 사용자가 방금 인증되었는지 감지하고 SessionAuthenticationStrategy를 호출합니다. 이로 인한 문제는 일반적인 설정에서 모든 요청에 대해 HttpSession을 읽어야 한다는 것을 의미합니다.
스프링 시큐리티 6에서는 기본적으로 인증 메커니즘 자체가 SessionAuthenticationStrategy를 호출해야 합니다. 이는 인증이 완료되었을 때를 감지할 필요가 없으며 따라서 모든 요청에 대해 HttpSession을 읽을 필요가 없음을 의미합니다.
SessionManagementFilter 벗어날 때 고려해야 할 사항
스프링 시큐리티 6에서는 기본적으로 SessionManagementFilter가 사용되지 않으므로, sessionManagement DSL의 일부 메소드는 아무런 효과가 없습니다.
sessionAuthenticationErrorUrl=> 인증 메커니즘에서 AuthenticationFailureHandler를 구성합니다.sessionAuthenticationFailureHandler=> 인증 메커니즘에서 AuthenticationFailureHandler를 구성합니다.sessionAuthenticationStrategy=> 인증 메커니즘에서 SessionAuthenticationStrategy를 구성합니다.
인증 정보 저장 위치 사용자 정의
기본적으로 스프링 시큐리티는 HTTP 세션에 보안 컨텍스트를 저장합니다. 그러나 이를 사용자 정의하고 싶은 몇 가지 이유가 있을 수 있습니다:
- HttpSessionSecurityContextRepository 인스턴스에 대해 개별 세터를 호출하고 싶을 수 있습니다.
- 수평 확장을 가능하게 하기 위해 캐시나 데이터베이스에 보안 컨텍스트를 저장하고 싶을 수 있습니다.
먼저, SecurityContextRepository의 구현을 생성하거나, HttpSessionSecurityContextRepository와 같은 기존 구현을 사용해야 합니다. 그런 다음, 이를 HttpSecurity에 설정할 수 있습니다.
SecurityContextRepository 사용자 정의하기
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
SecurityContextRepository repo = new MyCustomSecurityContextRepository();
http
// ...
.securityContext((context) -> context
.securityContextRepository(repo)
);
return http.build();
}
위의 구성은 SecurityContextHolderFilter와 UsernamePasswordAuthenticationFilter와 같은 참여하는 인증 필터에 SecurityContextRepository를 설정합니다. 무상태 필터에서도 설정하려면, 무상태 인증을 위한 SecurityContextRepository 사용자 정의 방법을 참고하세요.
인증 정보를 수동으로 저장하기
예를 들어, 스프링 시큐리티 필터에 의존하는 대신 사용자를 수동으로 인증하는 경우가 있을 수 있습니다. 이를 위해 사용자 정의 필터나 스프링 MVC 컨트롤러 엔드포인트를 사용할 수 있습니다. 요청 사이에 HttpSession에서 인증 정보를 저장하고 싶다면,
private SecurityContextRepository securityContextRepository =
new HttpSessionSecurityContextRepository();
@PostMapping("/login")
public void login(@RequestBody LoginRequest loginRequest, HttpServletRequest request, HttpServletResponse response) {
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(
loginRequest.getUsername(), loginRequest.getPassword());
Authentication authentication = authenticationManager.authenticate(token);
SecurityContext context = securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(authentication);
securityContextHolderStrategy.setContext(context);
securityContextRepository.saveContext(context, request, response);
}
class LoginRequest {
private String username;
private String password;
// getters and setters
}
- 컨트롤러에 SecurityContextRepository 추가하기
- HttpServletRequest와 HttpServletResponse를 주입하여 SecurityContext를 저장할 수 있도록 합니다.
- 제공된 자격증명을 사용하여 인증되지 않은 UsernamePasswordAuthenticationToken을 생성합니다.
- AuthenticationManager#authenticate를 호출하여 사용자를 인증합니다.
- SecurityContext를 생성하고 그 안에 Authentication을 설정합니다.
- SecurityContext를 SecurityContextRepository에 저장합니다. 그게 다입니다. 위 예제에서 securityContextHolderStrategy가 무엇인지 확실하지 않다면, 'Using SecurityContextStrategy' 섹션에서 더 자세히 알아볼 수 있습니다.
인증을 제대로 지우기
스프링 시큐리티의 로그아웃 지원을 사용하고 있다면, 컨텍스트를 지우고 저장하는 등 많은 작업을 대신 처리해 줍니다. 하지만, 수동으로 앱에서 사용자를 로그아웃해야 하는 경우가 있다면, 컨텍스트를 제대로 지우고 저장하고 있는지 확인해야 합니다.
무상태 인증을 위한 지속성 구성하기:
예를 들어, 요청 간에 인증을 유지하기 위해 HttpSession을 생성하고 유지할 필요가 없는 경우도 있습니다. HTTP Basic과 같은 일부 인증 메커니즘은 무상태이며, 따라서 매 요청마다 사용자를 재인증합니다.
세션을 생성하고 싶지 않다면, 다음과 같이 SessionCreationPolicy.STATELESS를 사용할 수 있습니다:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
http
// ...
.sessionManagement((session) -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
return http.build();
}
위 구성은 SecurityContextRepository를 NullSecurityContextRepository로 사용하도록 설정하고 세션에 요청이 저장되는 것을 방지합니다.
SessionCreationPolicy.NEVER를 사용하는 경우에도 애플리케이션이 여전히 HttpSession을 생성하고 있음을 알 수 있습니다. 대부분의 경우, 이는 인증이 성공한 후 인증된 리소스가 다시 요청되도록 요청이 세션에 저장되기 때문입니다. 이를 방지하려면, 요청이 저장되지 않도록 하는 방법을 참조하십시오.
세션에 무상태 인증 저장하기:
어떤 이유로 무상태 인증 메커니즘을 사용하고 있지만 여전히 세션에 인증 정보를 저장하고 싶다면, NullSecurityContextRepository 대신 HttpSessionSecurityContextRepository를 사용할 수 있습니다.
HTTP Basic의 경우, BasicAuthenticationFilter에서 사용하는 SecurityContextRepository를 변경하는 ObjectPostProcessor를 추가할 수 있습니다:
HTTP Basic 인증을 HttpSession에 저장하기:
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
http
// ...
.httpBasic((basic) -> basic
.addObjectPostProcessor(new ObjectPostProcessor<BasicAuthenticationFilter>() {
@Override
public <O extends BasicAuthenticationFilter> O postProcess(O filter) {
filter.setSecurityContextRepository(new HttpSessionSecurityContextRepository());
return filter;
}
})
);
return http.build();
}
위의 내용은 Bearer Token 인증과 같은 다른 인증 메커니즘에도 적용됩니다.
명시적 저장 필요 이해하기
스프링 시큐리티 5에서는 SecurityContext가 SecurityContextPersistenceFilter를 사용하여 자동으로 SecurityContextRepository에 저장되는 것이 기본 동작입니다. 저장은 HttpServletResponse가 커밋되기 직전과 SecurityContextPersistenceFilter 바로 전에 이루어져야 합니다. 불행히도, 요청 완료 전(즉, HttpServletResponse 커밋 직전)에 SecurityContext의 자동 저장은 사용자에게 놀라움을 줄 수 있습니다. 또한, 저장이 필요한지 여부를 결정하기 위해 상태를 추적하는 것이 복잡하여 때때로 SecurityContextRepository(즉, HttpSession)에 불필요한 쓰기가 발생합니다.
이러한 이유로 SecurityContextPersistenceFilter는 SecurityContextHolderFilter로 대체되도록 폐기되었습니다. 스프링 시큐리티 6에서는 기본적으로 SecurityContextHolderFilter가 SecurityContextRepository에서 SecurityContext를 읽고 이를 SecurityContextHolder에 채우기만 합니다. 이제 사용자는 요청 간에 SecurityContext를 유지하려면 SecurityContextRepository에 명시적으로 SecurityContext를 저장해야 합니다. 이는 모호성을 제거하고 필요할 때만 SecurityContextRepository(즉, HttpSession)에 쓰기를 요구함으로써 성능을 향상시킵니다.
작동 방식
requireExplicitSave가 true일 때, 스프링 시큐리티는 SecurityContextPersistenceFilter 대신 SecurityContextHolderFilter를 설정합니다.
동시세션 제어 설정
어플리케이션에서 단일 사용자의 로그인 능력에 제약을 가하고자 할 때, 스프링 시큐리티는 간단한 추가 설정으로 이를 지원합니다. 먼저, 세션 생명주기 이벤트에 대해 스프링 시큐리티를 업데이트 유지하기 위해 다음 리스너를 구성에 추가해야 합니다:
@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
그리고 보안 구성에 다음 줄을 추가합니다:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
http
.sessionManagement(session -> session
.maximumSessions(1)
);
return http.build();
}
이 설정은 사용자가 여러 번 로그인하는 것을 방지합니다 - 두 번째 로그인은 첫 번째 세션을 무효화합니다.
스프링 부트를 사용하여 위 구성 시나리오를 다음과 같이 테스트할 수 있습니다:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class MaximumSessionsTests {
@Autowired
private MockMvc mvc;
@Test
void loginOnSecondLoginThenFirstSessionTerminated() throws Exception {
MvcResult mvcResult = this.mvc.perform(formLogin())
.andExpect(authenticated())
.andReturn();
MockHttpSession firstLoginSession = (MockHttpSession) mvcResult.getRequest().getSession();
this.mvc.perform(get("/").session(firstLoginSession))
.andExpect(authenticated());
this.mvc.perform(formLogin()).andExpect(authenticated());
// 첫 번째 세션은 두 번째 로그인에 의해 종료됩니다.
this.mvc.perform(get("/").session(firstLoginSession))
.andExpect(unauthenticated());
}
}
또한 두 번째 로그인을 방지하고 싶은 경우 다음과 같은 설정을 사용할 수 있습니다:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
http
.sessionManagement(session -> session
.maximumSessions(1)
.maxSessionsPreventsLogin(true)
);
return http.build();
}
그러면 두 번째 로그인은 거부됩니다. "거부됨"은 사용자가 폼 기반 로그인을 사용하는 경우 인증 실패 URL로 전송된다는 의미입니다. 두 번째 인증이 "리멤버-미"와 같은 비대화형 메커니즘을 통해 이루어지는 경우, 클라이언트에게 "unauthorized" (401) 오류가 전송됩니다. 오류 페이지를 사용하고 싶다면, session-management 요소에 session-authentication-error-url 속성을 추가할 수 있습니다.
스프링 부트를 사용하여 위 구성을 다음과 같이 테스트할 수 있습니다:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class MaximumSessionsPreventLoginTests {
@Autowired
private MockMvc mvc;
@Test
void loginOnSecondLoginThenPreventLogin() throws Exception {
MvcResult mvcResult = this.mvc.perform(formLogin())
.andExpect(authenticated())
.andReturn();
MockHttpSession firstLoginSession = (MockHttpSession) mvcResult.getRequest().getSession();
this.mvc.perform(get("/").session(firstLoginSession))
.andExpect(authenticated());
// 두 번째 로그인은 방지됩니다.
this.mvc.perform(formLogin()).andExpect(unauthenticated());
// 첫 번째 세션은 여전히 유효합니다.
this.mvc.perform(get("/").session(firstLoginSession))
.andExpect(authenticated());
}
}
폼 기반 로그인에 사용자 정의 인증 필터를 사용하는 경우, 명시적으로 동시 세션 제어 지원을 구성해야 합니다. Maximum Sessions Prevent Login 샘플을 사용하여 시도해 볼 수 있습니다.
세션타임아웃 감지
세션은 자체적으로 만료되며, 보안 컨텍스트가 제거되도록 보장하기 위해 특별히 수행해야 할 작업은 없습니다. 그러나, 스프링 시큐리티는 세션이 만료되었을 때를 감지하고 지정된 특정 조치를 취할 수 있습니다. 예를 들어, 이미 만료된 세션으로 요청을 하는 사용자를 특정 엔드포인트로 리디렉션하고 싶을 수 있습니다. 이는 HttpSecurity의 invalidSessionUrl을 통해 달성됩니다.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
http
.sessionManagement(session -> session
.invalidSessionUrl("/invalidSession")
);
return http.build();
}
이 메커니즘을 사용하여 세션 타임아웃을 감지하는 경우, 사용자가 로그아웃한 후 브라우저를 닫지 않고 다시 로그인할 때 오류를 잘못 보고할 수 있습니다. 이는 세션을 무효화할 때 세션 쿠키가 지워지지 않기 때문에 사용자가 로그아웃한 후에도 제출될 수 있습니다. 이런 경우 로그아웃 시 세션 쿠키를 지우도록 로그아웃을 구성할 수 있습니다.
Invalid Session Strategy 사용자 정의
invalidSessionUrl은 SimpleRedirectInvalidSessionStrategy 구현을 사용하여 InvalidSessionStrategy를 설정하는 편리한 방법입니다. 행동을 사용자 정의하고 싶다면 InvalidSessionStrategy 인터페이스를 구현하고 invalidSessionStrategy 메서드를 사용하여 구성할 수 있습니다:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
http
.sessionManagement(session -> session
.invalidSessionStrategy(new MyCustomInvalidSessionStrategy())
);
return http.build();
}
로그아웃시 세션 쿠키 삭제
로그아웃 시 JSESSIONID 쿠키를 명시적으로 삭제할 수 있습니다. 예를 들어 로그아웃 핸들러에서 Clear-Site-Data 헤더를 사용하는 경우입니다:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
http
.logout((logout) -> logout
.addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(COOKIES)))
);
return http.build();
}
이 방법은 컨테이너에 구애받지 않고 어떤 컨테이너에서든 작동할 수 있는 이점이 있습니다. 대안으로, 로그아웃 핸들러에서 다음 구문을 사용할 수도 있습니다:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
http
.logout(logout -> logout
.deleteCookies("JSESSIONID")
);
return http.build();
}
불행히도, 이 방법은 모든 서블릿 컨테이너에서 보장되는 것은 아니므로 환경에서 테스트해야 합니다.
프록시 서버 뒤에서 애플리케이션을 운영하는 경우, 프록시 서버를 구성하여 세션 쿠키를 제거할 수도 있습니다. 예를 들어, Apache HTTPD의 mod_headers를 사용하는 경우, 로그아웃 요청에 대한 응답에서 JSESSIONID 쿠키를 만료시켜 삭제하는 지시문은 다음과 같습니다:
<LocationMatch "/tutorial/logout">
Header always set Set-Cookie "JSESSIONID=;Path=/tutorial;Expires=Thu, 01 Jan 1970 00:00:00 GMT"
</LocationMatch>
Session Fixation Attack Protection 이해하기
세션 고정 공격은 악의적인 공격자가 사이트에 접근하여 세션을 생성한 후 다른 사용자를 동일한 세션으로 로그인하도록 유도할 수 있는 잠재적 위험입니다(예를 들어, 세션 식별자가 포함된 링크를 보내는 방식). 스프링 시큐리티는 사용자가 로그인할 때 새로운 세션을 생성하거나 세션 ID를 변경함으로써 이를 자동으로 방지합니다.
Session Fixation Protection 설정
세션 고정 보호 전략을 선택함으로써 세션 고정 보호를 제어할 수 있으며, 세 가지 권장 옵션 중에서 선택할 수 있습니다:
- changeSessionId - 새 세션을 생성하지 않습니다. 대신 서블릿 컨테이너가 제공하는 세션 고정 보호(HttpServletRequest#changeSessionId())를 사용합니다. 이 옵션은 서블릿 3.1 (Java EE 7) 이상의 컨테이너에서만 사용할 수 있습니다. 구버전 컨테이너에서 이 옵션을 지정하면 예외가 발생합니다. 이는 서블릿 3.1 이상의 컨테이너에서 기본값입니다.
- newSession - 기존 세션 데이터를 복사하지 않고 새로운 "깨끗한" 세션을 생성합니다(스프링 시큐리티 관련 속성은 여전히 복사됩니다).
- migrateSession - 새 세션을 생성하고 기존 세션 속성을 모두 새 세션으로 복사합니다. 이는 서블릿 3.0 이하의 컨테이너에서 기본값입니다.
세션 고정 보호를 구성하는 방법은 다음과 같습니다:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
http
.sessionManagement((session) -> session
.sessionFixation((sessionFixation) -> sessionFixation
.newSession()
)
);
return http.build();
}
세션 고정 보호가 발생하면, 애플리케이션 컨텍스트에서 SessionFixationProtectionEvent가 발행됩니다. changeSessionId를 사용하는 경우, 이 보호 조치는 jakarta.servlet.http.HttpSessionIdListeners에게도 알려지므로, 코드가 두 이벤트를 모두 감지하고 있다면 주의가 필요합니다.
세션 고정 보호를 none으로 설정하여 비활성화할 수 있지만, 이는 권장되지 않으며 애플리케이션을 취약하게 만듭니다.
SecurityContextHolderStrategy 사용하기
다음 코드 블록을 고려해 보세요:
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
loginRequest.getUsername(), loginRequest.getPassword());
Authentication authentication = this.authenticationManager.authenticate(token);
// ...
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
- SecurityContextHolder를 통해 정적으로 SecurityContext 인스턴스를 생성합니다.
- SecurityContext 인스턴스에 Authentication 객체를 설정합니다.
- SecurityContext 인스턴스를 SecurityContextHolder에 정적으로 설정합니다.
위 코드는 잘 작동하지만, 원치 않는 효과를 낳을 수 있습니다: 컴포넌트가 SecurityContextHolder를 통해 정적으로 SecurityContext에 접근할 때, 여러 애플리케이션 컨텍스트가 SecurityContextHolderStrategy를 지정하고자 할 때 경쟁 상태가 발생할 수 있습니다. 이는 SecurityContextHolder에 클래스로더당 하나의 전략이 있기 때문이 아니라 애플리케이션 컨텍스트마다 하나의 전략이 있는 것이 아니라는 점에서 문제가 발생합니다.
이 문제를 해결하기 위해, 컴포넌트는 애플리케이션 컨텍스트에서 SecurityContextHolderStrategy를 연결할 수 있습니다. 기본적으로는 여전히 SecurityContextHolder에서 전략을 조회하게 됩니다.
이러한 변경사항은 대부분 내부적인 것이지만, 애플리케이션에서 SecurityContextHolderStrategy를 자동 연결하는 기회를 제공합니다. 이를 수행하려면 다음과 같이 코드를 변경해야 합니다:
public class SomeClass {
private final SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy();
public void someMethod() {
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(
loginRequest.getUsername(), loginRequest.getPassword());
Authentication authentication = this.authenticationManager.authenticate(token);
// ...
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(authentication);
this.securityContextHolderStrategy.setContext(context);
}
}
- SecurityContextHolderStrategy를 사용하여 빈 SecurityContext 인스턴스를 생성합니다.
- SecurityContext 인스턴스에 Authentication 객체를 설정합니다.
- SecurityContextHolderStrategy에 SecurityContext 인스턴스를 설정합니다.
Forcing Eager Session Creation (즉시세션생성)
때때로 세션을 즉시 생성하는 것이 가치가 있습니다. 이는 ForceEagerSessionCreationFilter를 사용하여 구성할 수 있으며, 다음과 같이 설정할 수 있습니다:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
http
.addFilter(new ForceEagerSessionCreationFilter());
return http.build();
}
이 필터는 요청이 들어올 때마다 즉시 HttpSession을 생성하도록 강제하여, 세션 생성이 지연되는 것을 방지합니다. 이는 특히 세션 생성 타이밍이 중요한 애플리케이션에서 유용할 수 있습니다.
이러한 설정들은 스프링 시큐리티의 유연성을 보여주며, 개발자가 자신의 애플리케이션 요구 사항에 맞게 보안 설정을 맞춤화할 수 있도록 지원합니다. 각 설정은 특정 애플리케이션의 보안 요구에 맞춰 조정될 수 있으며, 스프링 시큐리티의 기능을 최대한 활용할 수 있도록 돕습니다.