Search code examples
spring-bootoauth-2.0access-token

Hi,I am new to Spring boot. I need to create a rest template client that can get the oauth2 access token from an api link that is provided to me


I am new to Spring boot. I need to create a rest template client that can get the oauth2 access token from an api link that is provided to me

i have tried this code- logger.info("Inside RestTemplateDemo");

    HttpHeaders headers =new HttpHeaders();

    final String QPM_PASSWORD_GRANT = "?grant_type=password&username=username&password=password";
    String plainClientCredentials="client_id:client_password";
    String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes()));

    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();   

    //Add the Jackson Message converter
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

    // Note: here we are making this converter to process any kind of response, 
    // not only application/*json, which is the default behaviour
    converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));        
    messageConverters.add(converter);  
    restTemplate.setMessageConverters(messageConverters); 
    headers.add("Authorization", "Basic " + base64ClientCredentials);

    HttpEntity<String> request = new HttpEntity<String>(headers);
    ResponseEntity<Object> response = restTemplate.exchange("url"+QPM_PASSWORD_GRANT, HttpMethod.POST, request, Object.class);

    logger.info("response body of access token :: " + response.getBody());

    // Getting access token from response
    Gson gson = new Gson();
    Map map = gson.fromJson(response.getBody().toString(), Map.class);
    String access_token = (String) map.get("access_token");

    logger.info("access_token : " + access_token);

Solution

  • Use RestTemplate

    @Bean
    public RestTemplate createRestTemplate(){
      retrun new RestTemplateBuilder()
                    ...//do something for exm: add a ClientHttpRequestInterceptor or BasicAuthenticationInterceptor
                    .build();
    }
    

    to use it :

    @Autowired
    private RestTemplate restTemplate;
    
    /**
         *  getAccessToken
         *
         * @param userName 
         * @param password 
         * @return AuthResp 
         */
        public AuthResp getAccessToken(String userName, String password) {
            Map<String, String> params = new HashMap<>(5);
            params.put("grant_type", "password");
            params.put("username", userName);
            params.put("password", password);
            params.put("client_id", authConfig.getClientId());
            params.put("client_secret", authConfig.getSecret());
            AuthResp respDto = restTemplate.postForObject(getUrI(authConfig.getTokenUrl(), params), new HttpHeaders(), AuthResp.class);
            return respDto;
        }
    

    or use the feign or ribbon in spring-cloud