簡體   English   中英

OAuth令牌請求 - 從響應實體獲取access_token

[英]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;

}

我在使用從令牌網址請求OAuth訪問令牌的方法時遇到問題。 我實際上是通過access_token從服務器獲得響應,我在解析響應時遇到問題。

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

回報

{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}

我想要做的是將響應體轉換為JSONObject,這樣我就可以將access_token作為String。

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

似乎不起作用 - 結果是

{}

有人能指出我正確的方向嗎? 謝謝!

編輯:

編碼器 - 當我替換這些線時,我得到如下的堆棧跟蹤

 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

編碼器 - 嘗試最新的,我得到這個堆棧跟蹤

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

編碼器 - 請求來自Postman fyi

在此輸入圖像描述

注意:我可能會以錯誤的方式指出你。 請保留您的初始代碼並嘗試此操作

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

初步答案:

問題似乎是您正在使用Object類檢索響應實體。 將其修改為字符串類,並按如下方式進行休息調用:

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

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

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

編輯

根據LinkedMultiValueMap您可能必須在使用MultiValueMapLinkedMultiValueMap最終使用自定義實現。 而不是修改你的代碼如下。

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;

}

如果您需要澄清,請告訴我!

JSONObject jsonObject = new JSONObject();
String tokens[]=response.getBody().toString().replace("}","").replace("{","").split(",");
for(String s:tokens){
  String split = s.split("=");
  jsonObject.put(split[0],split[1]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM