简体   繁体   中英

Oauth2 Client in Spring security

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:

在此输入图像描述

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM