2016-08-02 4 views
3

OAuth2RestTemplate 객체를 사용하여 OAuth2 보안 REST 서비스 (다른 프로젝트에서 실행 중이고 다른 서버 등에서도 실행하도록 가정)를 사용하는 방법을 이해하려고합니다.OAuth2RestTemplate + Spring 4를 사용하는 방법?

f.e. 내 나머지 서비스는 다음과 같습니다 : -

https://localhost:8443/rest/api/user

>이 URL에 액세스하는 것은 내가에 갈 것 토큰을 요청하려면

을 인증하고 있지 않다으로 오류가 발생합니다 https://localhost:8443/rest/oauth/token?grant_type=password&client_id=test&client_secret=test&username= 사용자 이름 & password = PASSW 나는 다음 URL을 사용하여 REST API를 연결할 수있는 토큰을받은 후 ORD

나는 현재 시도

https://localhost:8443/rest/api/user?access_token=06

(예 : 토큰 삽입) 다음 개체가있는 항목 :

@EnableOAuth2Client 
@Configuration 
class MyConfig { 

    @Value("${oauth.resource:https://localhost:8443}") 
    private String baseUrl; 
    @Value("${oauth.authorize:https://localhost:8443/rest/oauth/authorize}") 
    private String authorizeUrl; 
    @Value("${oauth.token:https://localhost:8443/rest/oauth/token}") 
    private String tokenUrl; 

    @Bean 
    protected OAuth2ProtectedResourceDetails resource() { 

     ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails(); 

     List scopes = new ArrayList<String>(2); 
     scopes.add("write"); 
     scopes.add("read"); 
     resource.setAccessTokenUri(tokenUrl); 
     resource.setClientId("test"); 
     resource.setClientSecret("test"); 
     resource.setGrantType("password"); 
     resource.setScope(scopes); 

     resource.setUsername("test"); 
     resource.setPassword("test"); 

     return resource; 
    } 

    @Bean 
    public OAuth2RestOperations restTemplate() { 
     CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()) 
       .build(); 
     HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); 
     requestFactory.setHttpClient(httpClient); 
     AccessTokenRequest atr = new DefaultAccessTokenRequest(); 
     OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr)); 
     AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider(); 
     provider.setRequestFactory(requestFactory); 
     restTemplate.setAccessTokenProvider(provider); 
     return restTemplate; 
    } 

} 

아래의 컨트롤러에서 토큰을 얻으려고합니다.

@Controller 
public class TestController { 

    @Autowired 
    private OAuth2RestOperations restTemplate; 

    @RequestMapping(value="/", method= RequestMethod.GET) 
    public String TestForm() { 
     System.out.println("Token : " + restTemplate.getAccessToken().getValue()); 
    } 
} 

하지만 난 우리가 대신 ResourceOwnerPasswordResourceDetails의 다음 비밀번호를 부여해야하는 경우가지도하고있다 AccessTokenRequest을 (사용되어야한다는 발견 된 일부 블로그에서 예외

SEVERE: Servlet.service() for servlet [appServlet] in context with path [/web] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails cannot be cast to org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails] with root cause 
java.lang.ClassCastException: org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails cannot be cast to org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails 
    at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.obtainAccessToken(AuthorizationCodeAccessTokenProvider.java:190) 
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221) 
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173) 
    at com.divyshivglobalinvestor.web.controller.PersonalLoanController.PersonalLoanForm(PersonalLoanController.java:37) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:601) 
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) 
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) 
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114) 
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) 
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) 
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) 
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) 
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) 
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) 
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) 
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) 
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) 
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218) 
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) 
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) 
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) 
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) 
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) 
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) 
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442) 
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082) 
    at org.apache.coyote.AreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) 
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) 
    at java.lang.Thread.run(Thread.java:722)bstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623) 
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) 
    at java.util.concurrent.Th 

아래에 있어요 일회성). 누군가가 나를 액세스 토큰을 얻는 데 도움이된다면 좋을 것입니다. :)

미리 감사드립니다.

답변

2

당신은 응답을 restTemplate 콩에

+0

감사 ResourceOwnerPasswordAccessTokenProvider 대신 AuthorizationCodeAccessTokenProvider을 사용한다! 실용적인 예를 들어 주시겠습니까? –