简体   繁体   English

Spring安全中的Oauth2客户端

[英]Oauth2 Client in Spring security

I have troube finding example for OAuth2 client implemented using Spring. 我找到了使用Spring实现的OAuth2客户端的示例。

I have OAuth2 authorization and resource server implemented using Spring. 我使用Spring实现了OAuth2授权和资源服务器。 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. 我需要一个示例,如何仅使用客户端凭据从我的OAuth2服务器获取访问令牌。 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. 我发现只使用Java库的例子,但我认为在Spring的OAuth2框架中有支持。

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. 如果可能,示例应包含OAuth2客户端,OAuth2授权服务器和OAuth2资源服务器,所有这些都使用自签名证书通过TLS进行通信,使用Spring实现,不使用xml配置。

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. 通过Spring Security OAuth2库获取访问令牌是相当直接的,如下所示的示例代码。 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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