2016-05-30 43 views
13

İşletim sistemi Kimlik Bilgilerini içeren Oath2 kullanarak, Spring Boot üzerindeki mikro servislerimi korumaya çalışıyorum. Bu arada, bu mikroservisler sadece ara katman katmanları üzerinden birbirleriyle konuşacaktır, yani yetkilendirmeye izin vermek için kullanıcı kimlik bilgilerine gerek yoktur (Facebook olarak kullanıcı giriş süreci).Spring Boot + Oauth2 istemci kimlik bilgileri

Internet'te bu iletişimi yönetmek için nasıl yetkilendirme ve kaynak sunucusu oluşturulacağını gösteren örnekleri aradım. Ancak, kullanıcı kimlik bilgilerini (üç bacak) kullanarak nasıl yapılacağını açıklayan örnekler buldum.

Spring Boot ve Oauth2'de herhangi bir örnek nasıl yapılır? Kullanılan kapsamlar hakkında daha fazla ayrıntı vermek mümkün ise, jeton değişimi minnettar olacaktır.

cevap

14

Oauth2 İstemci kimlik bilgileriyle korunan REST hizmetlerine sahibiz. Kaynak ve yetkilendirme hizmeti aynı uygulamada çalışıyor ancak farklı uygulamalara bölünebilir. OAuth2 tablolar için

@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 yapılandırma:

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

kimlik & kaynak sunucusuyla iletişim izledi gider olarak

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

aşağıdaki kayıt OAuth2 Veritabanı mevcuttur:

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 
Sen OAuth2 güvenli hizmetine (uyumsuz) konuşmak için restTemplate enjekte edebilir

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

istemci uygulamasında

Resttemplate yapılandırması. Şu anda kapsamı kullanmıyoruz.

+1

Gerçekten güzel kod, Denemeyi deneyeceğim. –

+0

Verileri @ deue kullanarak ve oauthRestTemplate kullanarak ayarlamak yerine başka bir yol var mı? – Jesse

+0

@CarlosAlberto Merhaba Bunun için tüm projeye sahipsiniz. Aynı şeylere de ihtiyacım var. – noobdeveloper

İlgili konular