Java Spring Boot + Oauth2 客户端凭据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37534073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:25:40  来源:igfitidea点击:

Spring Boot + Oauth2 client credentials

javaspringspring-securityspring-bootoauth-2.0

提问by Carlos Alberto

I am trying to protect my microservices on Spring Boot using Oath2 with Client Credentials flow.

我正在尝试使用 Oath2 和客户端凭据流来保护 Spring Boot 上的微服务。

By the way, those microservices will only talk each other over the middleware layer, I mean no user credentials are needed to allow the authorization (user login process as Facebook).

顺便说一下,这些微服务只会通过中间件层相互交谈,我的意思是不需要用户凭据来允许授权(用户登录过程为 Facebook)。

I have looked for samples on the Internet showing how to create an authorization and resource server to manage this communication. However I just found examples explaining how to do it using user credentials (three legs).

我在 Internet 上查找了显示如何创建授权和资源服务器来管理此通信的示例。但是,我刚刚找到了一些示例,说明如何使用用户凭据(三条腿)来执行此操作。

Does anyone have any sample how to do it in Spring Boot and Oauth2? If it is possible give further details about the scopes used, token exchanging would be grateful.

有没有人有任何示例如何在 Spring Boot 和 Oauth2 中做到这一点?如果可以提供有关所用范围的更多详细信息,将不胜感激。

采纳答案by JohanB

We have REST services protected with Oauth2 Client credentials scheme. The Resource and authorization service are running in the same app, but can be split into different apps.

我们使用 Oauth2 客户端凭据方案保护 REST 服务。资源和授权服务在同一个应用程序中运行,但可以拆分到不同的应用程序中。

@Configuration
public class SecurityConfig {

@Configuration
@EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {

    // Identifies this resource server. Usefull if the AuthorisationServer authorises multiple Resource servers
    private static final String RESOURCE_ID = "*****";

    @Resource(name = "OAuth")
    @Autowired
    DataSource dataSource;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http    
                .authorizeRequests().anyRequest().authenticated();
        // @formatter:on
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID);
        resources.tokenStore(tokenStore());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }
}

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Resource(name = "OAuth")
    @Autowired
    DataSource dataSource;

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore());
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }
}
}

Datasource config for the Oauth2 tables:

Oauth2 表的数据源配置:

@Bean(name = "OAuth")
@ConfigurationProperties(prefix="datasource.oauth")
public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().build();
}

Communicating with authentication & resource server goes as followed

与身份验证和资源服务器的通信如下

curl -H "Accept: application/json" user:password@localhost:8080/oauth/token -d grant_type=client_credentials
curl -H "Authorization: Bearer token" localhost:8080/...

The following record is present in the Oauth2 Database:

Oauth2 数据库中存在以下记录:

client_id  resource_ids  client_secret  scope  authorized_grant_types   web_server_redirect_uri  authorities  access_token_validity refresh_token_validity  additional_information  autoapprove
user  ****  password  NULL  client_credentials  NULL  X  NULL  NULL  NULL  NULL

Resttemplate configuration in client application

客户端应用程序中的 Resttemplate 配置

@Configuration
@EnableOAuth2Client
public class OAuthConfig {

@Value("${OAuth2ClientId}")
private String oAuth2ClientId;

@Value("${OAuth2ClientSecret}")
private String oAuth2ClientSecret;

@Value("${Oauth2AccesTokenUri}")
private String accessTokenUri;

@Bean
public RestTemplate oAuthRestTemplate() {
    ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
    resourceDetails.setId("1");
    resourceDetails.setClientId(oAuth2ClientId);
    resourceDetails.setClientSecret(oAuth2ClientSecret);
    resourceDetails.setAccessTokenUri(accessTokenUri);

    /*

    When using @EnableOAuth2Client spring creates a OAuth2ClientContext for us:

    "The OAuth2ClientContext is placed (for you) in session scope to keep the state for different users separate.
    Without that you would have to manage the equivalent data structure yourself on the server,
    mapping incoming requests to users, and associating each user with a separate instance of the OAuth2ClientContext."
    (http://projects.spring.io/spring-security-oauth/docs/oauth2.html#client-configuration)

    Internally the SessionScope works with a threadlocal to store variables, hence a new thread cannot access those.
    Therefore we can not use @Async

    Solution: create a new OAuth2ClientContext that has no scope.
    *Note: this is only safe when using client_credentials as OAuth grant type!

     */

//        OAuth2RestTemplate restTemplate = new      OAuth2RestTemplate(resourceDetails, oauth2ClientContext);
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails, new DefaultOAuth2ClientContext());

    return restTemplate;
}
}

You can inject the restTemplate to talk (Asynchronously) to the Oauth2 secured service. We do not use scope at the moment.

您可以注入 restTemplate 以(异步)与 Oauth2 安全服务对话。我们目前不使用范围。