Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OAuth token request - get access_token from responseentity

public String requestAccessToken(String username, String password, String oauthaurl) {
    log.info("Request access token");
    String token = null;
    List<HttpMessageConverter<?>> converters = getMessageConverters();

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(converters);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> oauthPayload = new LinkedMultiValueMap<String, String>();
    oauthPayload.add("username", username);
    oauthPayload.add("password", password);
    oauthPayload.add("grant_type", "password");

    HttpEntity<?> request = new HttpEntity<>(oauthPayload, headers);
    ResponseEntity<?> response = restTemplate.postForEntity(oauthaurl, request, Object.class);
    log.info(response.getStatusCode().toString());
    log.info(response.getBody().toString());

    JSONObject jsonObject = new JSONObject(response.getBody());
    log.info(jsonObject.toString());

    //get access_token from jsonObject here

    return token;

}

I'm having trouble with my method that requests an OAuth access token from a token url. I'm actually getting a response back from the server with an access_token, I'm having trouble parsing the response.

log.info(response.getBody().toString());

returns

{access_token=EI79TeB_Vavu-vgl5WLp8CNWpLUWQBpS3Cm4uU-C1VCJkQJFEo2SthMjPN4gmvQ9ZpQu6Iku11mnvZSUKPVim0MsAEpcMbBdIWl3AMiXCfv9OeqfJRK_1wwIyjo5brDeHK8L5XJPsg98mEKL41qg2IW0Ks9TeYbkRyw4CFKwjcuTi3W3toLBlEGOEinNnrrj6bhOjwaaCVT7zWAIVoImXa-h0VTsoCn2XRVoCO7GENV-Qx55JzTFPJhe2sg72HgRbN8kTID_AcsN8wSKRTQ3T0N74Ks8dfs3YRx0NP4-ADByMcMEnyP8IGoCPHwANNwA8JpYaL2pijWBjOm7VSA53B9Knqxv1EYajBFYXfy74jYUFqlGTKLRUtuKomJh_d9OHM04V-q7xgtlg9upB3s9ORXjbTmzRDzq9U4P67FGJdQe4D4WKUju7oNtjkDzbQZEp0A9fxyHxHFI7MRP4mwPuxMldgytX8Oc1SqoakFre7qzxldaitWqKqnt217e7N7G, token_type=bearer, expires_in=1209599, userName=xxx, .issued=Thu, 02 Mar 2017 16:03:08 GMT, .expires=Thu, 16 Mar 2017 16:03:08 GMT}

What I'm trying to do is convert the response body to a JSONObject so I can get the access_token as a String.

JSONObject jsonObject = new JSONObject(response.getBody());
log.info(jsonObject.toString());

doesn't seem to work - the result is

{}

Can someone point me in the right direction? Thank you!

edit:

Coder - when I substitute those lines I get the stack trace as below

 2017-03-02 11:16:00.040  INFO 99914 --- [           main] c.u.e.service.EventRecor
 at [Source: java.io.PushbackInputStream@1a38c59b; line: 1, column: 1]
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270)
    at com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1234)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1122)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1075)
    at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:60)
    at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3798)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2922)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:237)
    ... 18 more

Coder - trying your latest, I get this stack trace

2017-03-02 11:16:00.040  INFO 99914 --- [           main] c.u.e.service.EventRecor
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
    at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
Caused by: org.springframework.web.client.HttpClientErrorException: 400 Bad Request
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:628)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:549)
    at com.comp.eventrecorder.service.EventRecorderServiceImpl.requestAccessToken(EventRecorderServiceImpl.java:182)
    at com.comp.eventrecorder.service.EventRecorderServiceImpl.startProcessing(EventRecorderServiceImpl.java:57)
    at com.comp.eventrecorder.Application.main(Application.java:32)
    ... 8 more

Coder - The request works from Postman fyi

enter image description here

like image 784
user619804 Avatar asked Mar 02 '17 16:03

user619804


1 Answers

Note: I might be pointing you in the wrong way. Do keep your initial code and try this

JSONObject jsonObject = new JSONObject(response.getBody().toString());
log.info(jsonObject.getString("access_token"));

Initial Answer:

The problem seems to be you are retrieving the response entity with Object class. Modify it to string class and make you rest call as follows:

ResponseEntity<String> response = restTemplate.postForEntity(oauthaurl, request, String.class);

JSONObject jsonObject = new JSONObject(response.getBody());

log.info(jsonObject.getString("access_token"));

Edit

As per the stacktrace you might have to end up using a custom implementation as you are using MultiValueMap and LinkedMultiValueMap. Instead of that modify your code as below.

public String requestAccessToken(String username, String password, String oauthaurl) {
    log.info("Request access token");
    String token = null;

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);



    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(oauthaurl)
                                                       .queryParam("grant_type", "password")
                                                       .queryParam("username", username)
                                                       .queryParam("password", password);

    URI myUri=builder.buildAndExpand().toUri();

    HttpEntity<?> request = new HttpEntity<>(headers);
    ResponseEntity<String> rs = restTemplate.exchange(myUri, HttpMethod.POST, request,String.class);
    JSONObject jsonObject = new JSONObject(rs.getBody());
    log.info(jsonObject.getString("access_token"));

    //get access_token from jsonObject here

    return token;

}

Let me know if you need clarification!!

like image 113
Coder Avatar answered Nov 15 '22 05:11

Coder