Oauth2 Client in Spring Security

I have a problem finding an example for an OAuth2 client implemented using Spring.

I have OAuth2 authorization and a resource server implemented using Spring. I want to get an access token from this authorization server. I need an example how to get the access token from my OAuth2 server using only client credentials. No user is involved in this, only my client application receives an access token using client credentials, and then uses it to access client resources .

I found only an example of using Java libraries, but I assume that there is support for this in the Spring OAuth2 environment.

If possible, the example should include an OAuth2 client, an OAuth2 authorization server, and an OAuth2 resource server, all of which communicate via TLS using a self-signed certificate implemented using Spring, without an xml configuration.

Here is the sequence diagram:

enter image description here

+6
source share
1 answer

Obtaining an access token through the Spring Security OAuth2 library is quite simple, as shown in the code example below. In this case, you only need the dependency

<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>2.1.0.RELEASE</version>
</dependency>

Sample code:

@Test
public void getAccessTokenViaSpringSecurityOAuthClient() {
    try{

        ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
        resourceDetails.setClientSecret(TestOAuthConstants.CLIENT_SECRET);
        resourceDetails.setClientId(TestOAuthConstants.CLIENT_ID);
        resourceDetails.setAccessTokenUri(TestOAuthConstants.TOKEN_REQUEST_URL);
        resourceDetails.setScope(TestOAuthConstants.SCOPES);

        OAuth2RestTemplate oAuthRestTemplate = new OAuth2RestTemplate(resourceDetails);

        org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
        headers.setContentType( MediaType.APPLICATION_JSON );

        OAuth2AccessToken token = oAuthRestTemplate.getAccessToken();
        System.out.println(oAuthRestTemplate.getResource());
        System.out.println(oAuthRestTemplate.getOAuth2ClientContext());
        System.out.println(token);

        assertTrue(token != null);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
+8
source

All Articles