9 Aralık 2019 Pazartesi

SpringSecurity OAuth2 Client OAuth2ClientConfigurer Sınıfı

Giriş
Şu satırı dahil ederiz
import org.springframework.security.config.annotation.web.configurers.oauth2.client.
OAuth2ClientConfigurer;
Facebook, Google gibi OAuth2 doğrulaması yapan sunucuları client olarak kullanabilmeyi sağlar. Açıklaması şöyle
The OAuth 2.0 Client features provide support for the Client role as defined in the OAuth 2.0 Authorization Framework.

The following main features are available:

- Authorization Code Grant
- Client Credentials Grant
- WebClient extension for Servlet Environments (for making protected resource requests)
Bu sınıf şu bileşenlere sahiptir
“ClientRegistration”
“ClientRegistrationRepository”

“OAuth2AuthorizedClient”
“OAuth2AuthorizedClientRepository / OAuth2AuthorizedClientService”
“RegisteredOAuth2AuthorizedClient”

“AuthorizationRequestRepository”
“OAuth2AuthorizationRequestResolver”
“OAuth2AccessTokenResponseClient”
Eğer bu sınıfı kullanmak istemezsek 
1. WebClient ile tüm bu sınıfları birleştirmek gerekir.
2. RestTemplate  ile tüm bu sınıfları birleştirmek gerekir.
Örnek
Elimizde şöyle bir kod olsun
@Configuration
public class OAuthClientConfiguration {

  @Bean
  ReactiveClientRegistrationRepository clientRegistrations(
    @Value("${spring.security.oauth2.client.provider.okta.token-uri}") String token_uri,
    @Value("${spring.security.oauth2.client.registration.okta.client-id}") String client_id,
    @Value("${spring.security.oauth2.client.registration.okta.client-secret}") String client_secret,
    @Value("${spring.security.oauth2.client.registration.okta.scope}") String scope,
    @Value("${spring.security.oauth2.client.registration.okta.authorization-grant-type}") String authorizationGrantType

  ) {
    ClientRegistration registration = ClientRegistration
      .withRegistrationId("okta")
      .tokenUri(token_uri)
      .clientId(client_id)
      .clientSecret(client_secret)
      .scope(scope)
      .authorizationGrantType(new AuthorizationGrantType(authorizationGrantType))
      .build();
    return new InMemoryReactiveClientRegistrationRepository(registration);
  }

  @Bean
  WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations) {
    InMemoryReactiveOAuth2AuthorizedClientService clientService = new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrations);
    AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager = 
      new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(clientRegistrations, clientService);
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
    oauth.setDefaultClientRegistrationId("okta");
    return WebClient.builder()
      .filter(oauth)
      .build();
  }
}
Kullanmak için şöyle yaparız
@Autowired
private WebClient webClient;

@Scheduled(fixedRate = 5000)
public void scheduledRequest() {
  webClient.get()
  .uri("http://localhost:8081")
  .retrieve()
  .bodyToMono(String.class)
  .map(string -> "Schedule request response: " + string)
  .subscribe(logger::info);
}
ClientRegistration
ClientRegistration yazısına taşıdım

OAuth2AuthorizedClient
Açıklaması şöyle
OAuth2AuthorizedClient serves the purpose of associating an OAuth2AccessToken (and optional OAuth2RefreshToken) to a ClientRegistration (client) and resource owner, who is the Principal end-user that granted the authorization.
AuthorizationRequestRepository
Açıklaması şöyle
AuthorizationRequestRepository is responsible for the persistence of the OAuth2AuthorizationRequest from the time the Authorization Request is initiated to the time the Authorization Response is received (the callback).
application.yml Dosyası
Şöyle yaparız.
spring:
  security:
    oauth2:
      client:
        registration:
          auth-server:
            client-id: webClient
            client-secret: clientSecret
            scope: read,write
            authorization-grant-type: authorization_code
            redirect-uri: http://localhost:8081/client/login/oauth2/code/auth-server
        provider:
          auth-server:
            authorization-uri: http://localhost:8080/auth-server/oauth/authorize
            token-uri: http://localhost:8080/auth-server/oauth/token
            user-info-uri: http://localhost:8082/resource-server/users/info
            user-name-attribute: user_name
Örnek
Şöyle yaparız.
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http...
      .and()
      .oauth2Login()
      .and()
      .oauth2Client()
      ...
  }
}
authorizationCodeGrant metodu
Açıklaması şöyle
http.oauth2Client().authorizationCodeGrant() is used for cases where an OAuth 2.0 client requires an access token, in order to initiate a call to a protected resource, but needs to be authorized by the Resource Owner first via the Authorization Code grant.
Örnek - authorizationRequestRepository
Açıklaması şöyle.
If you would like to provide a custom implementation of AuthorizationRequestRepository that stores the attributes of OAuth2AuthorizationRequest in a Cookie, you may configure it as shown in the following example:
Açıklaması şöyle
...as the documentation states AuthorizationRequestRepository is used to store the attributes of an OAuth2AuthorizationRequest which are clientId, redirectUri, scope and state. This is sent to the authorization server for an authorization code which is then sent in the form of an OAuth2AuthorizationCodeGrantRequest to obtain the access and refresh token in a OAuth2AccessTokenResponse model. In the final step the framework saves the tokens in an OAuth2AuthorizedClient model using the InMemoryOAuth2AuthorizedClientService...
Şöyle yaparız.
@EnableWebSecurity
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .oauth2Client()
        .authorizationCodeGrant()
          .authorizationRequestRepository(this.cookieAuthorizationRequestRepository())
    ...
  }

  private AuthorizationRequestRepository<OAuth2AuthorizationRequest>
    cookieAuthorizationRequestRepository() {
    return new HttpCookieOAuth2AuthorizationRequestRepository();
  }
}

Hiç yorum yok:

Yorum Gönder