Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authorization Bearer token in HttpClient?

I am trying to access an API using an oauth2 authorization token in Java Here is the client code

DefaultHttpClient httpclient = new DefaultHttpClient();  HttpPost post = new HttpPost("http://res-api"); post.setHeader("Content-Type","application/json"); post.setHeader("Authorization", "Bearer " + finalToken);  JSONObject json = new JSONObject(); // json.put ... // Send it as request body in the post request   StringEntity params = new StringEntity(json.toString()); post.setEntity(params);  HttpResponse response = httpclient.execute(post); httpclient.getConnectionManager().shutdown(); 

This returns a 401.

An equivalent curl command works with no issues with the same token:

curl -H "Content-Type:application/json" -H "Authorization:Bearer randomToken" -X POST -d @example.json http://rest-api 

I tried logging out the request and it looks like the authorization is set correctly

DEBUG [2016-06-28 20:51:13,655] org.apache.http.headers: >> Authorization: Bearer authRandomToKen; Path=/; Domain=oauth2-server; Expires=Wed, 29 Jun 2016 20:51:13 UTC 

I tried out the curl command by copy-pasting this same token and t works fine

Although I also see this line

DEBUG [2016-06-28 20:51:13,658] org.apache.http.impl.client.DefaultHttpClient: Response contains no authentication challenges 
like image 975
user_mda Avatar asked Jun 28 '16 20:06

user_mda


People also ask

How do I add Bearer Token in HTTP request?

Bearer token Bearer tokens enable requests to authenticate using an access key, such as a JSON Web Token (JWT). The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value.

What is HTTP authorization bearer?

Bearer authentication (also called token authentication) is an HTTP authentication scheme that involves security tokens called bearer tokens.

How do I send a POST request with Bearer Token authorization header C #/ net code?

POST JSON With Bearer Token Authorization Header [C#/. NET Code] To send a POST JSON request with a Bearer Token authorization header, you need to make an HTTP POST request, provide your Bearer Token with an Authorization: Bearer {token} HTTP header and give the JSON data in the body of the POST message.


2 Answers

I have come across similar situation, I was able to do it by following way, I hope this will help others.

import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL;  public class HttpURLConnectionExample {       public static void main(String[] args) throws Exception {          // Sending get request         URL url = new URL("http://example-url");         HttpURLConnection conn = (HttpURLConnection) url.openConnection();          conn.setRequestProperty("Authorization","Bearer "+" Actual bearer token issued by provider.");         //e.g. bearer token= eyJhbGciOiXXXzUxMiJ9.eyJzdWIiOiPyc2hhcm1hQHBsdW1zbGljZS5jb206OjE6OjkwIiwiZXhwIjoxNTM3MzQyNTIxLCJpYXQiOjE1MzY3Mzc3MjF9.O33zP2l_0eDNfcqSQz29jUGJC-_THYsXllrmkFnk85dNRbAw66dyEKBP5dVcFUuNTA8zhA83kk3Y41_qZYx43T          conn.setRequestProperty("Content-Type","application/json");         conn.setRequestMethod("GET");           BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));         String output;          StringBuffer response = new StringBuffer();         while ((output = in.readLine()) != null) {             response.append(output);         }          in.close();         // printing result from response         System.out.println("Response:-" + response.toString());      } } 
like image 163
Red Boy Avatar answered Sep 17 '22 14:09

Red Boy


I was trying to do something similar using HttpClient and I got it working by making a small change as below.

post.setHeader(HttpHeaders.CONTENT_TYPE,"application/json"); post.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + finalToken); 
like image 30
Nilucshan Siva Avatar answered Sep 20 '22 14:09

Nilucshan Siva