[서버] 스프링 RestTemplate org.springframework.web.client.HttpClientErrorException: 401 Unauthorized

프로그래밍/서버2021. 3. 1. 20:58

스프링에서 RestTemplate를 이용해서 REST API 테스트 중인데 아래의 에러가 발생했습니다.

 

정확한 원인을 알려주면 좋을텐데 좀 애매하게 알려주네요.

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 401 Unauthorized] with root cause

org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
	at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:766) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:724) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:680) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:600) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at com.dreamaz.gongga.auth.services.AuthService.isValidKakaoAccessToken(AuthService.java:55) ~[classes/:na]
	at com.dreamaz.gongga.auth.services.AuthService.isValidAccessToken(AuthService.java:31) ~[classes/:na]
	at com.dreamaz.gongga.auth.controller.AuthServiceController.getAuthStatus(AuthServiceController.java:25) ~[classes/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0-272]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0-272]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0-272]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0-272]
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:158) ~[spring-boot-actuator-2.0.3.RELEASE.jar:2.0.3.RELEASE]
	at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:126) ~[spring-boot-actuator-2.0.3.RELEASE.jar:2.0.3.RELEASE]
	at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:111) ~[spring-boot-actuator-2.0.3.RELEASE.jar:2.0.3.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90) ~[spring-boot-actuator-2.0.3.RELEASE.jar:2.0.3.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) [tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) [tomcat-embed-core-8.5.31.jar:8.5.31]
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.31.jar:8.5.31]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0-272]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0-272]
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.31.jar:8.5.31]
	at java.lang.Thread.run(Thread.java:748) [na:1.8.0-272]

 

아래의 부분이 중요한 것 같습니다.

org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
	at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:766) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:724) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:680) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:600) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]

 

디버깅 로그를 좀 더 자세히 보려면 아래의 과정이 필요합니다.

application.properties 에 아래의 코드를 추가합니다.

logging.level.org.apache.http=DEBUG
logging.level.httpclient.wire=DEBUG

만약 yaml 파일을 쓴다면 아래와 같이 추가해주세요.

logging:
  level:
    org.apache.http: DEBUG
    httpclient.wire: DEBUG

 

그리고 RestTemplate를 만들 때 setRequestFactory를 설정합니다.

RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

 

그러면 스프링 로그에서 추가 정보를 얻을 수 있습니다.

Request Header는 이상한 부분이 안보였습니다.

아래 로그는 Response 관련 로그입니다.

org.apache.http.wire                     : http-outgoing-0 << "HTTP/1.1 401 Unauthorized[\r][\n]"
org.apache.http.wire                     : http-outgoing-0 << "Date: Mon, 01 Mar 2021 11:39:47 GMT[\r][\n]"
org.apache.http.wire                     : http-outgoing-0 << "Server: Apache[\r][\n]"
org.apache.http.wire                     : http-outgoing-0 << "WWW-Authenticate: Bearer[\r][\n]"
org.apache.http.wire                     : http-outgoing-0 << "Caller-AppId: 10395[\r][\n]"
org.apache.http.wire                     : http-outgoing-0 << "Content-Type: application/json;charset=UTF-8[\r][\n]"
org.apache.http.wire                     : http-outgoing-0 << "Content-Length: 86[\r][\n]"
org.apache.http.wire                     : http-outgoing-0 << "Keep-Alive: timeout=10, max=500[\r][\n]"
org.apache.http.wire                     : http-outgoing-0 << "Connection: Keep-Alive[\r][\n]"
org.apache.http.wire                     : http-outgoing-0 << "[\r][\n]"
org.apache.http.wire                     : http-outgoing-0 << "{"msg":"ip mismatched! callerIp=123.33.327.41. check out registered ips.","code":-401}"
org.apache.http.headers                  : http-outgoing-0 << HTTP/1.1 401 Unauthorized
org.apache.http.headers                  : http-outgoing-0 << Date: Mon, 01 Mar 2021 11:39:47 GMT
org.apache.http.headers                  : http-outgoing-0 << Server: Apache
org.apache.http.headers                  : http-outgoing-0 << WWW-Authenticate: Bearer
org.apache.http.headers                  : http-outgoing-0 << Caller-AppId: 10395
org.apache.http.headers                  : http-outgoing-0 << Content-Type: application/json;charset=UTF-8
org.apache.http.headers                  : http-outgoing-0 << Content-Length: 86
org.apache.http.headers                  : http-outgoing-0 << Keep-Alive: timeout=10, max=500
org.apache.http.headers                  : http-outgoing-0 << Connection: Keep-Alive
o.a.http.impl.execchain.MainClientExec   : Connection can be kept alive for 10000 MILLISECONDS
o.a.http.impl.auth.HttpAuthenticator     : Authentication required
o.a.http.impl.auth.HttpAuthenticator     : kapi.kakao.com:443 requested authentication

 

{"msg":"ip mismatched! callerIp=123.33.327.41. check out registered ips.","code":-401}

이 부분이 핵심입니다.

 

디벨로퍼에서 정보좀 찾아보니 아래와 같네요 ㅎㅎ;;

devtalk.kakao.com/t/rest-api-ip-mismatched/105585

 

Kakao DevTalk_

카카오 데브톡. 카카오 플랫폼 서비스 관련 질문 및 답변을 올리는 개발자 커뮤니티 사이트입니다.

devtalk.kakao.com

developers-sample앱은 카카오에서 제공하는 샘플앱으로,
디벨로퍼스 내부에서만 테스트 할 수 있도록 IP가 제한되어 있습니다.

 

카카오 디벨로퍼 사이트에서 제공되는 액세스 토큰을 사용해서 생긴 문제였습니다.

제 앱에서 발급받은 액세스 토큰을 사용하니 문제가 사라졌습니다. ㅎㅎ;;

 

아래는 정상적인 response 로그입니다.

 

http-outgoing-0 << "HTTP/1.1 200 OK[\r][\n]"
http-outgoing-0 << "Date: Mon, 01 Mar 2021 12:06:48 GMT[\r][\n]"
http-outgoing-0 << "Server: Apache[\r][\n]"
http-outgoing-0 << "Quota-Type: PASS[\r][\n]"
http-outgoing-0 << "Content-Type: application/json;charset=UTF-8[\r][\n]"
http-outgoing-0 << "Content-Length: 94[\r][\n]"
http-outgoing-0 << "Keep-Alive: timeout=10, max=500[\r][\n]"
http-outgoing-0 << "Connection: Keep-Alive[\r][\n]"
http-outgoing-0 << "[\r][\n]"
http-outgoing-0 << "{"id":1507820123,"expiresInMillis":43159559,"expires_in":43159,"app_id":112413,"appId":112413}"
http-outgoing-0 << HTTP/1.1 200 OK
http-outgoing-0 << Date: Mon, 01 Mar 2021 12:06:48 GMT
http-outgoing-0 << Server: Apache
http-outgoing-0 << Quota-Type: PASS
http-outgoing-0 << Content-Type: application/json;charset=UTF-8
http-outgoing-0 << Content-Length: 94
http-outgoing-0 << Keep-Alive: timeout=10, max=500
http-outgoing-0 << Connection: Keep-Alive

 

 

참고

stackoverflow.com/questions/47104149/spring-resttemplate-get-raw-json-string

 

Spring restTemplate get raw json string

How can I get the raw json string from spring rest template? I have tried following code but it returns me json without quotes which causes other issues, how can i get the json as is. ResponseEnti...

stackoverflow.com

www.baeldung.com/spring-resttemplate-logging

 

Spring RestTemplate Request/Response Logging | Baeldung

A quick and practical guide to RestTemplate logging.

www.baeldung.com

 

작성자

Posted by 드리머즈

관련 글

댓글 영역