Feign Client 사용해서 카카오 로그인 구현 + Trouble Shooting

형준·2024년 2월 28일

Feign Client 사용

feign client는 annotation으로 사용할 수 있도록 구현되어 있습니다. 카카오 로그인에서 토큰을 가져오고 토큰을 이용해서 정보를 가져올 때 feign client를 이용했습니다.

1. 의존성 추가

  • spring boot 버전에 맞게 추가 (spring boot 2.7.7 사용)
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
implementation platform("org.springframework.cloud:spring-cloud-dependencies:2021.0.8")

2.

  • @EnableFeignClients annotation 추가하기
@EnableFeignClients
@SpringBootApplication
public class ProjectApplication {

	public static void main(String[] args) {
		SpringApplication.run(ProjectApplication.class, args);
	}

}

2. 토큰 가져오기

  • 카카오 서버에 http 요청을 해서 토큰을 가져올 수 있는 url과 파라미터들을 설정한다.
@Component
@FeignClient(name = "KakaoTokenFeignClient", url = "${oauth2.kakao.base-url}", configuration = KakaoFeignConfiguration.class)
public interface KakaoTokenFeignClient {

    @PostMapping(value = "/oauth/token")
    KakaoTokenResponse generateToken(@RequestParam(value = "grant_type") String grantType,
                                     @RequestParam(value = "client_id") String clientId,
                                     @RequestParam(value = "redirect_uri") String redirectUri,
                                     @RequestParam(value = "code") String code);

}

3. Configuration 파일 작성

  • cofiguration 파일을 이용해서 header를 설정할 수 있는 bean을 등록할수도 있고 여러가지 설정이 가능하다.
public class KakaoFeignConfiguration {
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            requestTemplate.header("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
        };
    }
    @Bean
    public ErrorDecoder errorDecoder() {
        return new FeignClientException();
    }

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

}

4. 프론트에서 요청할 수 있는 api 만들기

  • 프론트에서 코드를 받아오면 callback/kakao api를 호출하면서 코드를 넘겨주면 토큰을 받아오고 정보까지 받아올 수 있는 로직 작성
//memberController
    @GetMapping("/callback/kakao")
    public ResponseDTO<?> getKakaoAccount(@RequestParam("code") String code) {

        return memberService.getKakaoInfo(code);

    }
@Service
@RequiredArgsConstructor
public class KakaoOauthService  {

    private final KakaoInfoFeignClient kakaoInfoFeignClient;
    public KakaoProfile getKakaoUserInfo(String token) {
        KakaoProfile kakaoProfile = kakaoInfoFeignClient.getInfo(token);

        return kakaoProfile;
    }
}

5.정보 가져오기

  • 위에 KakaoOauthService에서 사용하는 kakaoInfoFeignClient 작성
    카카오 서버에서 토큰을 이용해서 http 요청을 보내서 정보를 가져온다.
@Component
@FeignClient(name = "KakaoFeignClient", url = "${oauth2.kakao.info-url}", configuration = KakaoFeignConfiguration.class)
public interface KakaoInfoFeignClient {

    @GetMapping("/v2/user/me")
    KakaoProfile getInfo(@RequestHeader(name = "Authorization") String Authorization);
}

Trouble shooting

  • Feign client를 이용해서 카카오 서버에 요청을 보내는데 자꾸 Feign Client Error가 발생해서 처음에는 요청이 안가는 줄 알고 Feign Client를 구현하는 글들을 많이 읽어 보았는데 코드에는 문제가 없었는 것 같았습니다.
  • 문제는 카카오 서버에 요청을 보낼 때 헤더와 rquest 바디에 담아서 보냈었는데 접근이 안되었는데 @RequestParam으로 이름을 지정해서 보냈더니 성공했습니다.
profile
백엔드 개발자가 되기 위한 경험을 기록하는 블로그입니다.

0개의 댓글