使用Spring oauth2使用OAuth安全的REST Web服务

时间:2015-07-16 11:20:23

标签: spring spring-mvc oauth-2.0 spring-boot jhipster

我想从服务器使用REST Web服务,该服务器使用oauth2来保护他的资源。

我使用Spring boot(JHipster)。

要做到这一点,我在SecurityConfiguration上课了这个:

@Value("${oauth.resource:http://sercverUsingOAuth2}")
private String baseUrl;

@Value("${oauth.authorize:http://sercverUsingOAuth2/rest/oauth/token}")
private String authorizeUrl;

@Value("${oauth.token:http://sercverUsingOAuth2/rest/oauth/token}")
private String tokenUrl;

@Bean
public OAuth2RestOperations oauth2RestTemplate() {
    AccessTokenRequest atr = new DefaultAccessTokenRequest();
    return new OAuth2RestTemplate(resource(),
            new DefaultOAuth2ClientContext(atr));
}

@Bean
protected OAuth2ProtectedResourceDetails resource() {
    AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
    resource.setAccessTokenUri(tokenUrl);
    resource.setUserAuthorizationUri(authorizeUrl);
    resource.setClientId("client_id");
    resource.setClientSecret("client_secret");
    resource.setGrantType("grant_type");
    return resource;
}

使用以下方法注释此类(SecurityConfiguration):

@Configuration
@EnableWebSecurity
@EnableOAuth2Client

这是我的controller(Spring MVC):

@RestController
@RequestMapping("/consume")
public class MyContrtoller {

@Inject
private OAuth2RestOperations oauth2RestTemplate;

@RequestMapping(value = "/oauth2", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<DataModel> getProducts() {

    ResponseEntity<MyModel> forEntity = oauth2RestTemplate
            .getForEntity("http://sercverUsingOAuth2/rest/resourceToConsume",
                    MyModel.class);
    return forEntity.getBody().getData();
}

}

但是,当我想要使用我的网络服务(http://myHost/consume/oauth2)时,我得到了这个例外:

    org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException:
 Unable to obtain a new access token for resource 'null'. The provider manager
 is not configured to support it.

我用Google搜索,我发现了这个:

但它对我没有帮助。

感谢。

0 个答案:

没有答案