How to send HTTP request using JWT token for authentication from cookie storage in android
Solution 1
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/
Solution 2
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);
Omkar
I am Android professional. I have been exploring Android since more than 5 years. Till date, I have developed more than 25 Android applications. Want to know more about me visit omkar.co
Updated on December 09, 2020Comments
-
Omkar over 3 years
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 JWTauth-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 returnBad 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:
Screenshot of cookie stored in Chrome
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. - Post, URL: