Authenticate data before upload on server in android - java

I am developing an android app in which, I am sending some text, files to server. I am using JSON to upload files to server. But I want to provide security to upload data. Data should only get uploaded from android device. In my case if I send data using postman it is get uploaded on server.
php developer told me that, "send data in header". I google it and I found some code.
Authentication.java
public class Authentication {
public void AuthenticateData(String url) {
HttpPost httppost = new HttpPost(url);
httppost.addHeader("userId","someName");
httppost.addHeader("secretKey","password");
}
}
And I am using it like this way.
Authentication authentication
URL = "url_to_upload_data";
JSONParser jParser = new JSONParser();
.
.
authentication.AuthenticateData(URL);
.
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("emailid", emailid));
param.add(new BasicNameValuePair("device_reg", deviceRegNo));
param.add(new BasicNameValuePair("message",message));"));
JSONObject json_Object = jParser.makeHttpRequest(URL, "POST", param);
Is this correct way to do it. Will it be secure?

The problem with your code is that AuthentificateData is not returning anything.
The problem of your approach is that you assume a password can be stored securely on the phone. If you place it in code, even after obfuscation anybody can decompile your sources and read the value.
To provide a secure transfer, you need to use asymmetric cryptography, also refereed as public key cryptography . The public key can be known by anyone and it is safe to store in the phone. You have to protect your server to not leak your private key.
To help in authentication you can also use digital signatures.
You do not have to implement them from scratch. You have here simple examples to get started.

Related

Post to SharePoint 2013 from Java

I've tried to connect to our SharePoint and POST some data to a list.
A user can interact with a Web-App and send some Information. These data will be send to a Java-Web-Interface running on a tomcat. The Java-Code should connect to our SharePoint and post the data in the list. Today, I read a lot of tutorials and ressources on the web... Most of them are deprecated ore discuss lightly different situations! SO! My mind whispered: "Go on and visit stackoverflow." And here I am, asking this question:
The Situation is described above. I call a web-Interface vie JS (angularJS) and pass an E-Mail-Adress which the user enters in the front-end. Here it goes in:
#Path("webservice")
public class SetEmail {
#POST
#Path("/SetEmail")
#Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8")
#Produces("text/plain")
public String addItem(String incoming) throws ClientProtocolException, IOException, AuthenticationException{
String result = "error";
JSONObject jsonObj = new JSONObject(incoming);
String listName = "Leads";
String username = "...";
char[] password= new char[]{'...', '...', ...};
String website = "...";
Now, after all I read, I have to get the DigestValue from SharePoint, because I want to make a POST-Request:
//Get the Digestvalue.
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY, new NTCredentials(username, password.toString(), "http://...", "https://..."));
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpPost httpPost = new HttpPost(website + "_api/contextinfo");
httpPost.addHeader("Accept", "application/json;odata=verbose");
httpPost.addHeader("content-type", "application/json;odata=verbose");
httpPost.addHeader("X-ClientService-ClientTag", "SDK-JAVA");
HttpResponse response = client.execute(httpPost);
byte[] content = EntityUtils.toByteArray(response.getEntity());
String jsonString = new String(content, "UTF-8");
System.out.println(response);
JSONObject json = new JSONObject(jsonString);
String FormDigestValue = json.getJSONObject("d").getJSONObject("GetContextWebInformation").getString("FormDigestValue");
After getting the Digest, I am able to execute the actual request:
//POST the data.
CloseableHttpClient client2 = HttpClients.createDefault();
HttpPost httpPost2 = new HttpPost(website + "_api/web/lists/GetByTitle(" + listName + ")");
httpPost2.setEntity(new StringEntity("test post"));
NTCredentials creds = new NTCredentials(username, password.toString(), "http://...", "https://...");
httpPost2.addHeader(new BasicScheme().authenticate(creds, httpPost2, null));
httpPost2.addHeader("X-RequestDigest", FormDigestValue);
httpPost2.addHeader("Accept", "application/json;odata=verbose");
httpPost2.addHeader("Content-Type", "application/json;odata=verbose");
CloseableHttpResponse response2 = client2.execute(httpPost2);
System.out.println(response2);
client2.close();
}
}
I know this isn't the most beautiful Code and yes, I am not an Java expert. My Problems are:
I don't know weather all of these code-Fragments are up to date or
weather I am using deprecated ones. Perhaps someone is able to
enlighten me.
I am using HttpClient from Apache. To me it looked like the most
usable library. Is that right?
Everytime I execute the Action on the front-end and my Code starts
running, I am getting an HTTP 401 Unauthorized error. I tried
various Kinds of Code but none worked well.
HttpResponseProxy{HTTP/1.1 401 Unauthorized [Server: Microsoft-IIS/8.0, SPR..
Perhaps someone has the Patience to tell me how to do it. Thank you.
Whoa... you are really trying some black magic here ;) - I would suggest you to get your HTTP POST / GET in a tool like Postman or some other REST tool working and then return to your code.
I don't know exactly what you are trying to achieve, but it might be easier to go via powershell (if you are trying to create a migration script) or JavaScript (if you are on a website).
Be aware that authentication differs in SharePoint online and SharePoint on premise... this is also customizable by your company (you can for example implement forms-based auth as well). Be sure to know what YOUR SharePoint is using. (Or share some more info, so we can help)

Encrypting Android app Data sent to MySQL DB

I have submitted an app to Amazon for approval, they came back with this:
"This app appears to be sending unencrypted, sensitive information. In this instance, the E-MAIL and PASSWORD, is being sent in clear text. Please update the app to encrypt all sensitive information."
On the server side, I encrypt the password in my database using the sha1() PHP method (pretty standard). I am assuming they want the password/email String that Java passes to be encrypted while in transit to the web service. I assume? If this is the case, I need to decrypt the data (specifically the email because this needs to be stored in my DB in plain text.
Has anyone seen this Amazon inquiry before? And is my explanation of it correct? And if so, is there a way in Java to temporary encrypt data while in transit?
Here is a sample in how I do it:
insertParam = new ArrayList<NameValuePair>();
insertParam.add(new BasicNameValuePair("Email", Email));
insertParam.add(new BasicNameValuePair("Password", Password));
insertParam.add(new BasicNameValuePair("Username", Username));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(insertParam));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
EDIT:
Looks like HTTPS is the way to go.
Amazon's requirement seems somewhat conservative, but could be best met by connecting to your web service via HTTPS instead of unencrypted HTTP. This is exactly what another StackOverflow user did in the end: Amazon AppStore Submission Failed: "Sensitive information like password is echoed in clear text without encryption"
While you could encrypt the data in your app, send it over the internet, and decrypt it on your server using a shared key, this is vulnerable to attackers that decompile your app to get the key.
Alternatively, you could generate a key pair, include the public key in the app and encrypt data with that, send it over the internet, and then use the private key on the server to decrypt the incoming data, but you're basically just re-implementing HTTPS manually.
At the end of the day, the "right" way to implement Amazon's requirement is to use HTTPS. Anything else is likely to be difficult to implement securely.

Using HttpClient to send JSON query string in a URL to a web service (Java)

I have a web service that I built... what I am trying to do now is send a simple request that contains a json query string from a Tapestry web app to that web service. I searched around and most people say to use Apache HttpClient to achieve this. Along with HttpClient I am using URIBuilder.
The Json object that I am trying to send looks like this
{"user":{"userEmail":"jdoe#gmail.com","firstName":"John","lastName":"Doe","phone":"203- 555-5555"},"password":"dead"}
*I realize the issues with the password being sent in plain text etc...
The url that works (tested by manually entering in a web browser and this web service already services an Android client and an iOS client) looks like this
http:// ##.##.###.##/createuser?json={"user":{"userEmail":"jdoe#gmail.com","firstName":"John","lastName":"Doe","phone":"203-555-5555"},"password":"dead"}
Here is the HttpClient code that I have mashed together from google'ing around trying to figure out why this wont work. Essentially what I am trying to do is create a URI with URIBuilder and then construct an HttpPost or HttpGet object with the newly built URI. But something is going wrong in the URIBuilding process. When I debug, an exception gets thrown when I try to set all the aspects of the URI.
Object onSuccess() throws ClientProtocolException, IOException, URISyntaxException{
// json = {"user":{"userEmail":"jdoe#gmail.com","firstName":"John","lastName":"Doe","phone":"203- 555-5555"},"password":"dead"}
String json = user.toJson();
URIBuilder builder = new URIBuilder();
// Error gets thrown when I step over the next line
builder.setScheme("http").setHost("##.###.##.###").setPort(8080).setPath("createuser").setQuery("json=" +json);
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
DefaultHttpClient httpClient = new DefaultHttpClient();
String tmp = request.getURI().toString();
HttpResponse response = httpClient.execute(request);
index.setResponse(EntityUtils.toString(response.getEntity()));
return index;
The error that comes back when I step over the line that I commented in the code is
[ERROR] TapestryModule.RequestExceptionHandler Processing of request failed with uncaught exception:org.apache.http.client.utils.URLEncodedUtils.parse(Ljava/lang/String;Ljava/nio/charset/Charset;)Ljava/util/List;
java.lang.NoSuchMethodError:org.apache.http.client.utils.URLEncodedUtils.parse(Ljava/lang/String;Ljava/nio/charset/Charset;)Ljava/util/List;
I have tried a lot of other combinations of methods and objects to get this request to send off to the server correctly and nothing seems to work. Hopefully I am overlooking something relatively simple.
Thanks in advance for any guidance you can provide.
You most likely have the wrong version or two versions of the apache httpcomponents on your classpath. If you are running Tapestry it will print out all packages on the classpath on the error page. Investigate there, find which httpcomponents is loaded, figure out where it comes from and fix it.
If this does not work, you should share some of your runtime environment with us. Which servlet engine, running from which IDE or are you running from the command line. Are you using Maven? If so share your pom. Etc.

Java: Sending facebook credentials

I am working on a program that will download a facebook page so I have the html. However, when I download it, I get the facebook page that isn't logged in.
Is there a way to somehow send my facebook login so facebook thinks the program is logged in, so I get the correct html?
If you want to get information from Facebook, you should be using the API available to you at https://developers.facebook.com/docs/
. The API provides access to most data that you would want, and it does so with OAuth authentication and JSON responses, which both have a lot of support in the development community (you will be able to find several libraries to handle these types of data without having to code it yourself). There are also samples, SDKs for a number of different programming language, and lots of good information.
Otherwise, if you want the HTML specifically, you can use the components at http://hc.apache.org/httpcomponents-client-ga/index.html
. This is some code that you can use to get a HTTP page...
HttpGet request = new HttpGet("http://www.facebook.com");
// Send the request
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
// Get the response code
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// Success
String responseMessage = EntityUtils.toString(response.getEntity());
// do something with the response here
}
If you need to send data, such as sending the login information to Facebook, you can use HttpPost instead of HttpGet, and attach your login information.
You should be warned, however, that Facebook is pretty strict at banning people that use HTTP requests rather than their API, so I would discourage you away from doing this. I direct you to the Facebook Platform Policy here... https://developers.facebook.com/policy/
You should look at the Facebook API: https://developers.facebook.com/

Get data from PHP script in JAVA

I am fairly new to Android programming and was wondering how I can get data from an SQL database in my Android app.
I currently have a PHP script that pulls the data I want from the SQL table but I'm not sure how to pull the data from the PHP script into my Java. How do I do this? I read something about SOAP. Is this the protocol I want to use?
Thanks
It depends. Where's the database, on the device, or on a server? If it's on the server, is the PHP code already a web app, or is it just a script?
In general, if the database is on the device, throw out the PHP and use JDBC to grab the data directly from Java. If the data is on the server, then turn the PHP script into a web app, and access that web app from Java. SOAP is certainly one protocol you can use for this, albeit a complex one that's often overkill. JSON or just plain text are many times better choices.
You can use the function below to get content from your PHP script
public static String get(String from) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(from);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) return EntityUtils.toString(resEntityGet);
} catch (Exception e) {
Log.e("", e.toString());
}
return null;
}

Categories

Resources