Reputation: 87
I have created an API to get bearer token and use the token on the same API as I got the token, here is the controller I have created:
@GetMapping("/getNik")
public String pushToken() {
//generate token
String uri = "http://some-url-to-get-token";
String notEncoded ="*****:******";
String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());
System.out.println("encodeUserPass "+encodedAuth);
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("client_id", "client_id");
headers.set("Authorization", "Basic "+encodedAuth);
HttpEntity<String> result = new HttpEntity<String>(headers);
String token = restTemplate.postForObject(uri, result, String.class);
Object obj=JSONValue.parse(token);
JSONObject jsonObject = (JSONObject) obj;
String access_token = (String) jsonObject.get("access_token");
//dapat token
System.out.println("baru di get "+access_token);
//hit get nik
String urix = "http:/some-url-that-need-otp-to-access";
RestTemplate restTemplatex = new RestTemplate();
HttpHeaders headersx = new HttpHeaders();
headersx.setContentType(MediaType.APPLICATION_JSON);
headersx.set("Authorization", "Bearer "+access_token);
System.out.println("initokennya "+access_token);
HttpEntity<String> resultx = new HttpEntity<String>(headersx);
System.out.println("sama?"+resultx);
//fail
String get = restTemplatex.getForObject(urix ,String.class, resultx);
return get;
}
The problem is when I got the token, I try to hit the API, but I can't use it, error 401 Unauthorized is there something I missed?
Upvotes: 1
Views: 206
Reputation: 234
try with this
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken);
Upvotes: 1