Spring Boot + Oauth2客户端凭据 [英] Spring Boot + Oauth2 client credentials

查看:1743
本文介绍了Spring Boot + Oauth2客户端凭据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有Client Credentials流的Oath2保护我在Spring Boot上的微服务。

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

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

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).

我在互联网上寻找样本,展示了如何创建授权和资源服务器来管理这种通信。但是我刚刚找到了解释如何使用用户凭据(三条腿)来解释它的示例。

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).

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

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.

推荐答案

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

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.

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

Oauth2表的数据源配置:

Datasource config for the Oauth2 tables:

@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/...

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

The following record is present in the Oauth2 Database:

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

@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;
}
}

你可以将restTemplate注入talk(异步)到Oauth2安全服务。
我们目前不使用范围。

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

这篇关于Spring Boot + Oauth2客户端凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆