giancarloparma

Untitled

Jan 17th, 2021 (edited)
927
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package it.giancarloparma.config;
  2.  
  3. import java.io.IOException;
  4. import java.nio.charset.StandardCharsets;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import java.util.function.Function;
  8.  
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.beans.factory.annotation.Value;
  12. import org.springframework.boot.web.client.RestTemplateBuilder;
  13. import org.springframework.context.annotation.Bean;
  14. import org.springframework.context.annotation.Configuration;
  15. import org.springframework.http.HttpRequest;
  16. import org.springframework.http.client.ClientHttpRequestExecution;
  17. import org.springframework.http.client.ClientHttpRequestInterceptor;
  18. import org.springframework.http.client.ClientHttpResponse;
  19. import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager;
  20. import org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService;
  21. import org.springframework.security.oauth2.client.OAuth2AuthorizationContext;
  22. import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
  23. import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
  24. import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
  25. import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider;
  26. import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
  27. import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
  28. import org.springframework.security.oauth2.client.registration.ClientRegistration;
  29. import org.springframework.security.oauth2.client.registration.ClientRegistration.Builder;
  30. import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
  31. import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
  32. import org.springframework.security.oauth2.core.AuthorizationGrantType;
  33. import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
  34. import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
  35. import org.springframework.util.StringUtils;
  36. import org.springframework.web.client.RestTemplate;
  37.  
  38. @Configuration
  39. public class GPRestTemplateConfig {
  40.     @Value("${gp.token-uri}")
  41.     private String accessTokenUri;
  42.  
  43.     @Value("${gp.client-id}")
  44.     private String clientId;
  45.    
  46.     @Value("${gp.registration-id}")
  47.     private String registrationId;
  48.    
  49.     @Value("${gp.principal}")
  50.     private String principal;
  51.    
  52.     @Value("${gp.username}")
  53.     private String username;
  54.    
  55.     @Value("${gp.password}")
  56.     private String password;
  57.    
  58.     @Bean
  59.     public OAuth2AuthorizedClientManager authorizedClientManager() {
  60.         String tokenUri = accessTokenUri;
  61.         Builder b = ClientRegistration.withRegistrationId(registrationId);
  62.         b.authorizationGrantType(AuthorizationGrantType.PASSWORD);
  63.         b.clientAuthenticationMethod(ClientAuthenticationMethod.POST);
  64.         b.tokenUri(tokenUri);
  65.         b.clientId(clientId);
  66.         ClientRegistrationRepository clients = new InMemoryClientRegistrationRepository(b.build());
  67.        
  68.         OAuth2AuthorizedClientService service = new InMemoryOAuth2AuthorizedClientService(clients);
  69.         AuthorizedClientServiceOAuth2AuthorizedClientManager manager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(
  70.                 clients, service);
  71.         OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
  72.                 .password().refreshToken().build();
  73.         manager.setAuthorizedClientProvider(authorizedClientProvider);
  74.         manager.setContextAttributesMapper(new Function<OAuth2AuthorizeRequest, Map<String, Object>>() {
  75.  
  76.             @Override
  77.             public Map<String, Object> apply(OAuth2AuthorizeRequest authorizeRequest) {
  78.                 Map<String, Object> contextAttributes = new HashMap<>();
  79.                 String scope = authorizeRequest.getAttribute(OAuth2ParameterNames.SCOPE);
  80.                 if (StringUtils.hasText(scope)) {
  81.                     contextAttributes.put(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME,
  82.                             StringUtils.delimitedListToStringArray(scope, " "));
  83.                 }
  84.                
  85.                 String username = authorizeRequest.getAttribute(OAuth2ParameterNames.USERNAME);
  86.                 if (StringUtils.hasText(username)) {
  87.                     contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
  88.                 }
  89.                
  90.                 String password = authorizeRequest.getAttribute(OAuth2ParameterNames.PASSWORD);
  91.                 if (StringUtils.hasText(password)) {
  92.                     contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
  93.                 }
  94.                
  95.                 return contextAttributes;
  96.             }
  97.            
  98.         });
  99.        
  100.         return manager;
  101.     }
  102.      
  103.     @Bean
  104.     public RestTemplate restTemplate(RestTemplateBuilder builder, OAuth2AuthorizedClientManager manager) {
  105.         RestTemplate restTemplate = builder.build();
  106.         restTemplate.getInterceptors().add(new BearerTokenInterceptor(manager, username, password, registrationId));
  107.  
  108.         return restTemplate;
  109.     }
  110.    
  111.     public class BearerTokenInterceptor implements ClientHttpRequestInterceptor {
  112.         private OAuth2AuthorizedClientManager manager;
  113.         private OAuth2AuthorizeRequest authorizeRequest;
  114.        
  115.         public BearerTokenInterceptor(OAuth2AuthorizedClientManager manager, String username, String password, String registrationId) {
  116.             this.manager = manager;
  117.             this.authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(registrationId)
  118.                     .attribute(OAuth2ParameterNames.USERNAME, username)
  119.                     .attribute(OAuth2ParameterNames.PASSWORD, password)
  120.                     .principal(principal).build();
  121.         }
  122.  
  123.         @Override
  124.         public ClientHttpResponse intercept(HttpRequest request, byte[] bytes, ClientHttpRequestExecution execution)
  125.                 throws IOException {
  126.             OAuth2AuthorizedClient client = manager.authorize(authorizeRequest);
  127.             if (client == null) {
  128.                 throw new IllegalStateException("Can't access the API without an authorized client");
  129.             }
  130.            
  131.             String accessToken = client.getAccessToken() != null ? client.getAccessToken().getTokenValue() : null;
  132.             if (accessToken != null) {
  133.                 request.getHeaders().add("Authorization", "Bearer " + accessToken);
  134.                 return execution.execute(request, bytes);
  135.             } else {
  136.                 throw new IllegalStateException("Can't access the API without an access token");
  137.             }
  138.         }
  139.        
  140.     }
  141. }
  142.  
RAW Paste Data