how to send/POST JWT token from Android to Laravel backend - android

i wanted to access my back-end using android phone. at this moment i want to do two things:
login the mob app after being authenticated from the Back-end.
Upload data to the back-end (back-end is PHP with Laravel Framework).
i first send email and password to the backend and gotten back a response of JWT token as shown:
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cLzE5Mi4xNjguMS4xMDI6ODAwMFwvYXBpXC92M1wvYXV0aGVudGljYXRlIiwiaWF0IjoxNDY2MDA5OTY3LCJleHAiOjE0NjYwMTM1NjcsImp0aSI6IjZjYjBlMTRjYTNkMjAzM2Q4OWM0NzM1M2ZjNjMzZTU2In0.GJGUjgy8U-uqjLSqJcysDTmgrNvxBHH03iBflLjsOwA"
Once the above token returned to the mob app, i want to send the same returned token for further post request, because the above jwt token is my key for accessing the back-end.
So my problem lies on sending the same token back to the back-end. it seems simple and stright forward since i have already started to communicate with my back end, and i have also checked my response by using post man.
and i can also got the user cridential using the jwt token on postman.
now the same token which works on postman is not working for my android. i know that my httpClient and httpPost are working since i have already send the email and password with it. i also know that my android post request is reaching the server since my returned result comes with an error message i built for an accepted token request, as shown below.
as you can see from the above snap shot. i first get the token inside a quotation (first highlighted), when posted for authentication. so i removed the quotation and posted the same token for getting user cridential but this time i got an error response which i built it on the Back-end.
so that is why i think my token is not going to the server properly. but i couldn't fix the problem. but i am guessing the token size is big, with a length of 490. so how shall i attach my token with the httpPost request? my code for the building the request is shown below:
public String getJsonString2(String url, String jwtString) {
String jsonString = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List nameValuePair = new ArrayList(1);
nameValuePair.add(new BasicNameValuePair("token", jwtString));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
jsonString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
return jsonString;
}
i have also tried using MultipartEntityBuilder for parsing the parameter (token in my case) but the MultipartEnityBuilder library was crasshing my program when building:
the MultipartEnityBuilder library is added to my project using the following dependencies:
//for accessing the MultipartEntity lbrary
compile "org.apache.httpcomponents:httpcore:4.2.4"
compile "org.apache.httpcomponents:httpmime:4.3"
the error because of the MultipartEntity
So now my question is:
how can i send the jwt token value from android to Laravel backend.

Perhaps try using MultipartEntity instead and create a "part" for the token. I have adapted this closely related answer to your case:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
//here you create the token body
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("token", jwtString, ContentType.TEXT_PLAIN);
HttpEntity reqEntity = builder.build();
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
I hope this helps, please give it a try and let me know.
You can visit this blog on Multipart Upload with HttpClient and learn more.

i have managed to solve my problem by simply setting the Authorization header with the token:
public String getJsonString2(String url, String jwtString) {
String jsonString = "";
// Creating HTTP client and post
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Authorization", "Bearer \\{" + jwtString + "\\}");
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
jsonString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
System.out.println("Http String content: " + jsonString);
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
return jsonString;
}

Related

Hide JSON file from public; only access for my Android app

I want to hide my JSON file from the public. So that noone can download this JSON data or go through the browser in my JSON file.
I want only that my own developed app can get the information of this JSON file.
Is there a way to code this? Thanks for answering.
what you need to do is to use token which is only known to your server and your client (mobile app) while making call to your server to get the json data. checkout the following tutorial on how to fetch data from server using token.
android token authentication
retrofit token authentication
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://yourbackend.example.com/tokensignin");
try {
List nameValuePairs = new ArrayList(1);
nameValuePairs.add(new BasicNameValuePair("idToken", idToken));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
final String responseBody = EntityUtils.toString(response.getEntity());
Log.i(TAG, "Signed in as: " + responseBody);
} catch (ClientProtocolException e) {
Log.e(TAG, "Error sending ID token to backend.", e);
} catch (IOException e) {
Log.e(TAG, "Error sending ID token to backend.", e);
}
Or add a token to retrofit NetworkInterceptor
builder.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addHeader("Authorization", authToken);
}
});
}

Android HTTP PUT not sending JSON request to server resulting in HTTP 405 Method not allowed

Android HTTP PUT not sending JSON request to server resulting in HTTP 405 Method not allowed.
Below is my async task background code
HttpClient httpclient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut("URL");
String jsonresponse = "";
try {
StringEntity se = new StringEntity(gson.toJson(resultPojo).toString());
se.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httpPut.setEntity(se);
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httpPut);
HttpEntity httpEntity = response.getEntity();
jsonresponse = EntityUtils.toString(httpEntity);
System.out.println("res .... "+jsonresponse);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
serverside code :
#POST
#Path("{id}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response submitUserResponse(#PathParam("userId") int userId,
#PathParam("id") int id, List<ResultPojo> responses) {
try {
//core logic goes here
return Response.status(Response.Status.CREATED).build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
Alright just like what was discussed it is most likely a mismatch different HTTP methods, in this case A Put and a post, whenever you ever encounter that HTTP code(405) do perform a validation on the methods you used, it happens.405 errors often arise with the POST method. You may be trying to introduce some kind of input form on the Web site, but not all ISPs allow the POST method necessary to process the form.A request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.

httpclient.execute(httpPost) error

In my android application I try to send a json object to a distant server, when I run it I get an error in httpclient.execute(httpPost)
This is a part of my code.
public static String GET(String url , JSONObject js){
try {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Authorization", "Basic **********");
httpPost.setEntity(new StringEntity(js.toString()));
HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(httpPost);
} catch (Exception e) {
Log.i("Console", "Error");
}
Any help please.
I guess your Problem is, that you try to run your Network Request from your Main Thread.
I would discourage you to use the Apache HTTP Client at all.
It became deprecated for Marshmallow, see here
Maybe try OkHttp. It offers you the possibility to run a request asynchronously.

How to make a web request sending a HASH key and get a Response Android

I've searched everywhere on how to make this happen but with no results.
First I need to make a request to a website then send a hash (which I already have) and get a response with some data.
I was able to connect but I'm not able to use the hash key to get the data.
Can anyone help me how to do this using android?
Thanks.
I tried to follow this:Make an HTTP request with android
using a host
The solution:
final HttpClient client = new DefaultHttpClient();
final HttpPost postMethod = new HttpPost(URL);
postMethod.setEntity(new StringEntity(postData, "utf-8"));
String responseData = "";
try {
final HttpResponse response = client.execute(postMethod);
responseData = EntityUtils.toString(response.getEntity(), "utf-8");
} catch(final Exception e) {
// handle exception here
}
This is an example of what you can do:
final String URL = "http://192.168.0.100:8000/myHistory/mobile/?user=";
HttpClient client;
StringBuilder url = new StringBuilder(URL);
url.append(user);
url.append("&pwd=");
url.append(hash);
client = new DefaultHttpClient();
HttpGet get = new HttpGet(url.toString());
HttpResponse response = null;
try {
response = client.execute(get);
} catch (IOException e) {
e.printStackTrace();
}
int status = 0;
status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = "";
try {
data = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
//Here you manipulate the 'data' variable, which is in HTML format.
It depends on which kind of hash you are using (SHA-N, MD5, etc) and the kind of framework you are using to build the server. Try to search on the documentation of your framework which kind of cryptographic hash function is used. Then search on internet an API that implements this cryptographic hash function on your code (e.g., Django uses PBKDF2). After that, you need to define the parameters of this function (salt, number of iterations, password (or hash)). The algorithm calculates the hash (password) using the salt and number of iterations values. So when you are trying to access a server you have to send via HTTP the hash that was generated. If this hash is the same hash generated on the server side, then the authentication is successful.

Using HttpGet returning complete HTML code

I am trying to invoke a private web-service in which there's one link I've to access using GET method. While using the direct URL on browser (needs to login first), I get the data in JSON format. The URL I am invoking is like this
http://www.example.com/trip/details/860720?format=json
The url is working fine, but when I invoke this using HttpGet, I am getting the HTML coding of the webpage, instead of the JSON String. The code I am using is as follows:
private String runURL(String src,int id) { //src="http://www.example.com/trip/details/"
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(src);
String responseBody="";
BasicHttpParams params=new BasicHttpParams();
params.setParameter("domain", token); //The access token I am getting after the Login
params.setParameter("format", "json");
params.setParameter("id", id);
try {
httpget.setParams(params);
HttpResponse response = httpclient.execute(httpget);
responseBody = EntityUtils.toString(response.getEntity());
Log.d("runURL", "response " + responseBody); //prints the complete HTML code of the web-page
} catch (Exception e) {
e.printStackTrace();
}
return responseBody;
}
Can you tell me what am I doing wrong here??
Try specify Accept & Content-Type in you http header:
httpget.setHeader("Accept", "application/json"); // or application/jsonrequest
httpget.setHeader("Content-Type", "application/json");
Note that you can use tools like wireshark capture and analyse the income and outcome http package, and figure out the exact style of the http header that returns your json response from a standard browser.
Update:
You mentioned need login first when using browser, the html content returned is probably the login page (if use basic authentication type, it returns a short html response with status code 401, so a modern browser knows how to handle, more specifically, pop up login prompt to user), so the first try would be checking the status code of your http response:
int responseStatusCode = response.getStatusLine().getStatusCode();
Depend on what kind of authentication type you use, you probably need specify login credentials in your http request as well, something like this (if it is a basic authentication):
httpClient.getCredentialsProvider().setCredentials(
new AuthScope("http://www.example.com/trip/details/860720?format=json", 80),
new UsernamePasswordCredentials("username", "password");

Categories

Resources