Oauth2 Client in Spring security

10,874

It is fairly straightfoward to get an access token via Spring Security OAuth2 library as the sample code shown below. The only dependency you need in this case is

<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();
    }
}
Share:
10,874
Nikola Lošić
Author by

Nikola Lošić

Updated on July 19, 2022

Comments

  • Nikola Lošić
    Nikola Lošić almost 2 years

    I have troube finding example for OAuth2 client implemented using Spring.

    I have OAuth2 authorization and resource server implemented using Spring. I want to get access token from that authorization server. I need an example how to get access token from my OAuth2 server using only client credentials. There is no user involved, just my client app getting access token using client credentials and then using it to access client resources.

    I found only example using Java libraries, but I assume there is support for that in Spring's OAuth2 framework.

    If possible, example should contain OAuth2 client, OAuth2 Authorization server and OAuth2 resource server, all communicating over TLS using self signed certificate, implemented using Spring, using no xml configuration.

    Here is the sequence diagram:

    enter image description here