Authorization Bearer token in HttpClient?
Asked Answered
N

3

43

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
Naissant answered 28/6, 2016 at 20:44 Comment(9)
Try verifying the network call using something like wireshark, both CURL and Java should look the same. Most likely Authorization header is not sent. Try hard coding it with the one in CURL.Concavoconvex
thanks for the pointers, I edited the question with the suggestion.s No luckNaissant
can you get the Response Header? It seems the request header is not recognized yet.Agro
Should the response header also contain the auth token? I just tried logging it and it doesntNaissant
looks like non of the headers are setNaissant
Use Fiddler to check the outgoing request.Cordillera
The auth header is sent and I can see it in the wire logs. It may be that its not recognized by the server. Any hints on why that can happen?Naissant
Any new on this important question?Disengage
I'd suggest a Chrome web extension Boomerang to test this. I use it daily at work for this exactly same issue.Callaway
M
36

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());

    }
}
My answered 12/9, 2018 at 11:13 Comment(1)
The above code works fine. But Eclipse wanted me to throw a try/catch around it.Denicedenie
C
27

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);
Commination answered 25/3, 2020 at 8:15 Comment(1)
This worked for me. Didn't know that had to concat the String "Bearer " before the token.Gamelan
D
3
I have implemented above given code for receiving Pipedream SSE real time events.Below The Below Code is working fine in Eclipse WITHOUT a 401 ERROR.

package //////YOUR PACKAGE NAME HERE/////

    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("https://your Server website");
        
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization","Bearer PLACE.HERE");
        
        //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) {
            System.out.println("Response:-" + output.toString());
    ////you will get output in "output.toString()" ,Use it however you like
        }
        in.close();
        
    }
}
Disdain answered 23/11, 2021 at 16:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.