WebClient 내부 호출 문제

🚨 문제 상황

기존 filter를 이용한 현재 로그인 정보를 이용하여 webClient 호출 시 로그인 할 때 webClient를 사용하는 경우, 현재 로그인 정보가 없기 때문에 에러 발생

기존 코드 일부

private ExchangeFilterFunction authorizationHeaderFilter() {
    return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

🧑‍💻 문제 분석

  1. 이전 코드는 기존 Filter를 이용하여 현재 로그인 정보를 사용. 하지만 로그인 과정에서 UserAuth 도메인 사이의 webclient 내부 요청은 기존 로그인 정보가 존재 X
  2. webclient를 사용하는 부분은 전부 도메인 내부에서의 연결이기 때문에 webclient를 사용할 때는 SpringSecurity를 우회하는 방법을 사용하면 되겠다 판단.

✅ 문제 해결

webclient config

		return WebClient.builder()
			.baseUrl("<http://localhost:8080>") // 기본 URL 설정
			.clientConnector(new ReactorClientHttpConnector(httpClient))
			.defaultHeader("WebclientInternal", passwordEncoder.encode(webSecretKey))
			.build();

JwtFilter

    String key = request.getHeader("WebclientInternal");
		if (passwordEncoder.matches(webSecretKey, testKey)) {
			log.info("내부 webClient 호출 성공");
			// webClient 용 내부 인증 객체 생성
			Authentication webclientAuth = new UsernamePasswordAuthenticationToken(
				"webclient-internal",
				null,
				List.of(new SimpleGrantedAuthority("ROLE_WEBCLIENT"))
			);
			SecurityContextHolder.getContext().setAuthentication(webclientAuth);

			filterChain.doFilter(request, response);
			return;
		}