Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Post, URL: http://iitjeeacademy.com/iitjeeacademy/api/v1/login
  • Headers: Content-Type:application/json
  • Request body (raw): {"password":"123","type":"student","email":"[email protected]"}

After login getting response using:

  • Get, URL: http://iitjeeacademy.com/iitjeeacademy/api/v1/student/me

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.

like image 467
Omkar Avatar asked Sep 15 '15 13:09

Omkar


People also ask

Can we send JWT token in GET request?

To send JSON web token (JWT) in an Axios GET request, we can add it to the headers. to call axios. get with the url and config . In config , we add the headers by setting the headers property to an object that has the Authorization header set to the token value.

Can I use JWT with Cookies?

On every request to server, the JWT will be read from Cookies and added in the Authorization header using Bearer scheme. The server can then verify the JWT in the request header (as opposed to reading it from the cookies).

How use JWT token for authentication and Authorization?

To authenticate a user, a client application must send a JSON Web Token (JWT) in the authorization header of the HTTP request to your backend API. API Gateway validates the token on behalf of your API, so you don't have to add any code in your API to process the authentication.


1 Answers

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/

like image 64
jaygeek Avatar answered Nov 17 '22 06:11

jaygeek