RestTemplate 으로 application/x-www-form-urlencoded 타입 요청 전송하기 (ITDA 프로젝트)

yeon·2021년 8월 24일
0

ITDA 카카오 oauth 구현 중 access token이 잘 안받아지는 문제

401 Unauthorized: [{"error":"invalid_client","error_description":"Bad client credentials","error_code":"KOE010"}] 에러가 발생

카카오 로그인 문서를 보면 client secret 값이 유효하지 않아서 발생하는 에러라고 한다.

RestTemplate을 사용해서 요청에 필요한 값들을 객체로 만들어서 전송하고 있다.

KakaoAccessTokenRequest request = new KakaoAccessTokenRequest(GRANT_TYPE, clientId, REDIRECT_URI, code, clientSecret);

AccessToken accessToken = restTemplate.postForObject(ACCESS_TOKEN_URI, new HttpEntity<>(request), KakaoAccessTokenResponse.class);

다시 카카오 문서를 보니 Content-type: application/x-www-form-urlencoded;charset=utf-8 form 타입으로 요청을 보내라고 한다.

위와 같이 RestTemplate의 postForObject에 KakaoAccessTokenRequest 객체를 담아 요청을 보내고 보니 요청의 Content-Type 이 application/json로 보내고 있다. 이것이 access token을 받아오지 못하는 원인인 듯 하다.

객체 대신 MultiValueMap에 필요한 파라미터를 담고 요청을 보내보니 Content-type: application/x-www-form-urlencoded 으로 보내진다.

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", GRANT_TYPE);
params.add("client_id", clientId);
params.add("client_secret", clientSecret);
params.add("redirect_uri", REDIRECT_URI);
params.add("code", code);

AccessToken accessToken = restTemplate.postForObject(ACCESS_TOKEN_URI, params, KakaoAccessTokenResponse.class);

결론: RestTemlate을 이용해서 application/x-www-form-urlencoded 타입으로 요청을 보낼때는 MutiValueMap을 이용하라.


참고: https://enterkey.tistory.com/276

0개의 댓글