2016-05-30 21 views
13

私は、クライアント証明書フローを持つOath2を使用して、Springブートでマイクロサービスを保護しようとしています。Springブート+ Oauth2クライアントの資格情報

ところで、これらのマイクロサービスはミドルウェアレイヤーを介してしか話をしません。つまり、承認を許可するためにユーザーの資格情報は必要ありません(Facebookとしてのユーザーログインプロセス)。

私は、この通信を管理するための承認とリソースサーバーの作成方法を示すインターネット上のサンプルを探しました。しかし、私はちょうどユーザーの資格情報(3つの足)を使用してそれを行う方法を説明する例を見つけました。

誰かがSpring BootとOauth2でどのようにサンプルを作成するのですか?可能な場合は、使用されているスコープについてさらに詳しく説明すると、トークンの交換は感謝します。

答えて

14

Oauth2クライアント資格スキームで保護されたRESTサービスがあります。リソースと認証サービスは同じアプリで実行されていますが、異なるアプリに分割することもできます。 OAuth2テーブルの

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

データソースの設定:

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

認証&リソースサーバとの通信が続く

curl -H "Accept: application/json" user:[email protected]:8080/oauth/token -d grant_type=client_credentials 
curl -H "Authorization: Bearer token" localhost:8080/... 

ようになり、次のレコードがの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 
0123クライアントアプリケーション

@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設定あなたは安全なのOAuth2サービスに(非同期)話をするrestTemplateを注入することができます。 現在、スコープは使用していません。

+1

本当に素敵なコード、私はそれを試してみるつもりです。 –

+0

@valueを使用してデータを取得し、oauthRestTemplateを設定する代わりに、他の方法がありますか? – Jesse

+0

@CarlosAlbertoこんにちは、これは完全なプロジェクトです。私も同じことが必要です。 – noobdeveloper

関連する問題