Omkar
Omkar

Reputation: 1543

How to send HTTP request using JWT token for authentication from cookie storage in android

What I did so far:

I am trying to communicate with Java web application which has custom authentication. In that, I need to first hit a link with request body parameters JSON type to get JWT auth-token in my cookies.

I have tested connection in Postman, I am receiving proper JSON response. But when I try same in my android application it return Bad Request error.

For Postman testing:

For login and getting auth-token in cookie storage:

After login getting response using:

Screenshot of cookie stored in Postman: Postman screenshot of stored cookie

Screenshot of cookie stored in Chrome enter image description here

Following are my HttpURLConnection request codes in android:

"Post" method, this connection is used to get auth-token. This method returns 200 Response.

HttpURLConnection connection = null;
try {
        // Created URL for connection.
        URL url = new URL(link);

        // Input data setup
        byte[] postData = request.getBytes(StandardCharsets.UTF_8);
        int postDataLength = postData.length;

        // Created connection
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        connection.setUseCaches(false);

        // loaded inputs
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.write(postData);
        wr.flush();
        wr.close();

        // getting a response
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK){
            // Read response
            response = convertToString(connection.getInputStream());
            return response;
        }else{
            // Read Error
            String response = connection.getResponseMessage();
            return response;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        Log.v("MalformedURL ---> ", e.getMessage());
    } catch (ProtocolException p) {
        p.printStackTrace();
        Log.v("Connection ---> ", p.getMessage());
    } catch (IOException i) {
        i.printStackTrace();
        Log.v("IO Exception ---> ", i.getMessage());
    } finally {
        connection.disconnect();
    }

"Get" method, must have auth-token in session cookies to get response. This method gives an 401 Unauthorized Error.

HttpURLConnection connection = null;
try{
        // Created URL for connection
        URL url = new URL(link);

        // Created connection
        connection = (HttpURLConnection) url.openConnection();
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("charset", "utf-8");

        // getting a response
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK){
            response = convertToString(connection.getInputStream());
            return response;
        }else{
            // Read Error
            String response = connection.getResponseMessage();
            return response;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException p) {
        p.printStackTrace();
    } catch (IOException i) {
        i.printStackTrace();
    } finally {
        connection.disconnect();
    }

Question: How to use stored JWT Token from cookies in HttpURLConnection android to get response from web service.

Upvotes: 7

Views: 56150

Answers (2)

jimmont
jimmont

Reputation: 2543

Building on jaygeek's answer (set the Authorization header and 'Bearer ' prefix) with an overly simplified JavaScript-client example:

localStorage.jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ';

fetch('/api/example', {method: 'POST',
headers: {
   'Authorization':`Bearer ${localStorage.jwt}`,
   'Content-type':'application/json'
}, body: JSON.stringify({stuff:'things'})
})
.then(console.log).catch(console.error);

function jwtRequest(url, token){
    var req = new XMLHttpRequest();
    req.open('get', url, true);
    req.setRequestHeader('Authorization','Bearer '+token);
    req.send();
}

jwtRequest('/api/example', localStorage.jwt);

Upvotes: 4

jaygeek
jaygeek

Reputation: 1172

I'm sure you've moved on, but...

For JWT auth, I'd send an HTTP Request header formatted as:

Authorization: Bearer jwtHeader.jwtPayload.jwtSignature

EXAMPLE:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

The specification and details are available at: https://jwt.io/introduction/

Upvotes: 22

Related Questions