• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    해결됨

SecurityContextHolderStrategy 설명해주신 부분에서 기존 방식 변경 방식에 대한 질문입니다.

24.05.11 14:41 작성 24.05.11 15:28 수정 조회수 107

0

안녕하세요, 24:00 에 말씀해주시는 SecurityContextHolderStrategy 사용하기부분에 기본방식과 변경방식 설명해주시는 부분에서 이해가 안되는 부분이 생겨 질문드립니다.

기존방식과 변경방식의 구현된 소스코드를 보니 내부에서(SecurityContextHolder.crateEmptyContext() 내부) 도 결론적으로는 strategy.createEmptyContext() 를 delegate 하는 방식으로 호출 되는것을 보았습니다. 6.x, 5.x, 4.x 모두 동일한듯합니다.

	/**
	 * Allows retrieval of the context strategy. See SEC-1188.
	 * @return the configured strategy for storing the security context.
	 */
	public static SecurityContextHolderStrategy getContextHolderStrategy() {
		return strategy;
	}

	/**
	 * Delegates the creation of a new, empty context to the configured strategy.
	 */
	public static SecurityContext createEmptyContext() {
		return strategy.createEmptyContext();
	}

AbstractAuthenticationProcessingFilter 쪽에서 successfulAuthentication 쪽에 로직dl 6.x, 5.7 이하 버전 대가 다른단것은 확인했는데

/**
	 * Puts the <code>Authentication</code> instance returned by the authentication
	 * manager into the secure context.
	 */
	protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
			Authentication authResult) throws IOException, ServletException {
		this.logger.debug(LogMessage.format("Authentication success: %s", authResult));
		SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
		context.setAuthentication(authResult);
		this.securityContextHolderStrategy.setContext(context);
		this.securityContextRepository.saveContext(context, request, response);
		if (this.eventPublisher != null) {
			this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
		}
		if (this.authenticationSuccessHandler != null) {
			this.authenticationSuccessHandler.onAuthenticationSuccess(request, response, authResult);
		}
	}
/**
	 * Puts the <code>Authentication</code> instance returned by the authentication
	 * manager into the secure context.
	 */
	protected void successfulAuthentication(HttpServletRequest request,
			HttpServletResponse response, Authentication authResult) throws IOException, ServletException {
		if (logger.isDebugEnabled()) {
			logger.debug("Authentication success: " + authResult);
		}
		SecurityContextHolder.getContext().setAuthentication(authResult);
		// Fire event
		if (this.eventPublisher != null) {
			eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
					authResult, this.getClass()));
		}

		if (authenticationSuccessHandler != null) {
			authenticationSuccessHandler.onAuthenticationSuccess(request, response, authResult);
		}
	}

추측건데 strategy 쪽을 세팅할수있는 부분이 추가됨에따라 달라진 부분이라 생각이 되어 이부분도 말씀하신 의도와는 다를듯하여

	/**
	 * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
	 * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
	 *
	 * @since 5.8
	 */
	public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
		Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
		this.securityContextHolderStrategy = securityContextHolderStrategy;
	}

경쟁조건 때문이라고 설명하신 부분에서 말씀하시는 의도를 다시 한번 알수있을까요.

답변 2

·

답변을 작성해보세요.

0

이건 공식문서에서 설명하고 있는 내용 그대로를 강의에서 풀어 설명하고 있습니다

아주 중요한 내용은 아니며 참고로 아시면 되는 내용입니다

스프링에서 어플리케이션 컨텍스트를 다중으로 계층화하여 구성 할 수 있는데 이 경우 각 어플리케이션 컨텍스트마다 SecurityContextHolderStrategy 전략을 다르게 설정한다고 했을 때 SecurityContext 참조 시 바로 접근하게 되면 스레드간 충돌이 일어날 수 있다고 보는 것입니다

이 때 SecurityContextHolderStrategy 를 먼저 참조하고 SecurityContext 에 접근하면 각 어플리케이션 컨텍스에 설정된 SecurityContextHolderStrategy 가 자동으로 Autowired 된 상태에서 SecurityContext 에 접근되도록 해 주기 때문에 스레드간 충돌이 나지 않는다는 의미입니다

그러나 일반적인 상황에서는 거의 일어나지 않기 때문에 침고 정도만 해도 됩니다

램쥐뱅님의 프로필

램쥐뱅

질문자

2024.05.15

네 관련 내용 다시 살펴보겠습니다. 감사합니다

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2024.05.13

안녕하세요, 인프런 AI 인턴입니다.

제공된 정보 중에는 SecurityContextHolderStrategy에 대한 구체적인 설명이 없어, 질문에 대한 직접적인 답변을 제공하기 어렵습니다. 하지만, 스프링 시큐리티를 사용하는 과정에서 SecurityContextHolder의 전략(SecurityContextHolderStrategy)을 설정하거나 변경하는 부분은 스프링 시큐리티의 커스터마이징과 관련된 중요한 부분 중 하나입니다.

일반적으로, SecurityContextHolder는 애플리케이션의 현재 보안 컨텍스트를 저장하는 데 사용되며, 이 컨텍스트에는 현재 인증된 사용자에 대한 정보가 포함됩니다. SecurityContextHolderStrategySecurityContextHolder가 내부적으로 사용하는 전략으로, 보안 컨텍스트의 저장 및 조회 방식을 결정합니다. 이 전략을 통해 개발자는 애플리케이션에 가장 적합한 방식을 선택하거나 커스텀 전략을 구현하여 사용할 수 있습니다.

질문하신 내용에서 언급된 “경쟁조건”은 멀티 스레드 환경에서 동시에 여러 작업이 수행될 때 발생할 수 있는 보안 문제 중 하나를 지칭합니다. 스프링 시큐리티에서 제공하는 전략을 적절히 설정하거나 변경함으로써, 보안 컨텍스트의 안정적인 관리 및 경쟁 조건에 대한 보호를 강화할 수 있습니다.

구체적인 구현 방법이나 전략 변경에 대한 자세한 지침은 스프링 시큐리티 공식 문서를 참조하시는 것이 가장 좋습니다. 예를 들어, 스프링 시큐리티의 버전 업그레이드를 고려할 때 변경된 API나 기능 등을 확인해보시는 것이 좋습니다.

또한, SecurityContextHolder, SecurityContextHolderStrategy에 대한 이해를 높이고자 한다면, 스프링 시큐리티 공식 문서나 관련 기술 블로그, 오픈 소스 프로젝트의 코드 등을 참고하시는 것도 도움이 될 수 있습니다.