can i make a server side form validation in firebase? - java

i am using httpUrlConnection in android to send a user form (name,pre name,email etc) to the server then validation is done at server side, after that form data are inserted to data base or an error returned to user. that is what my php page looks like in brief
<?php
$name = $_POST['name'];
$prename = $_POST['prename'];
$email = $_POST['email'];
if( isvalid($name)&&isvalid($prename)&&isvalid($email) ){
insertUser($name,$prename,$email);
echo 'successfully registered'
}else{
echo 'data invalid please correct';
}
?>
theoretically , now user cant insert malformed data like a name that contain numbers into my database.
even if a hacker could trick the host server into accepting such malformed input then mysql server will return an error that said could not insert those data into corresponding fields since every column has a predefined type in mysql.
now i considered to switch to firebase and i wonder if i can do the same verification before inserting the data into my realtime database without relying on client side verification. i mean if someone crack my app or bypass the verification on the client side(witch is easy for a hacker) and trick the app he could be able to insert some malformed data and users will start to see name that contain numbers or phone number that contain letter or have a password that have one letter and i dont want that to happen.
my question is: is there any way to verify the users inputs before inserting them to my firebase without a client side verification?
if not then what is the best way to get around that 'problem'?
Sorry for Lengthening,but i tried to be precise as mutch as possible.

To validate the data that can be written into the Firebase Realtime Database, you can use Firebase's server-side security rules. These are evaluated before every read/write to the database, and you can use them to ensure all data is valid, and all access is authorized.
For some examples, have a look at the Firebase documentation on validating the data with security rules.

Related

Cloudant Unathorized request

I've been trying to work this problem out about accessing my cloudant DB from IBM-bluemix services.
I've set my URL in Android studio like this:
URL url = new URL("https://XXXX-XXXX-XXXX-XXXX-XXXX-bluemix.cloudant.com");
And then trying to access it by:
CloudantClient client = ClientBuilder.url(url)
.username("myusername")
.password("mypassword")
.build();
However, When i try to access/modify anything within my database,
ex:
client.createDB("test_DB");
I get the error:
Error: unauthorized. Reason: one of _admin, server_admin is required for this request.
What am i missing?
I've seen many different ways to approach querying from cloudant, but this is the closest i've gotten.
Have i just completely misunderstood how querying from an existing database works?
If you are using a Cloudant legacy API key you won't be able to perform account administrator level actions, such as listing or creating databases because the legacy API keys are associated with specific databases not the account. If that is the type of credentials you are using you can initialize the client in the way you have done and get the existing database via:
Database db = client.database("test_DB", false);
Try your credentials using curl on the command line (see https://cloud.ibm.com/docs/services/Cloudant/tutorials?topic=cloudant-databases#databases)
Verify if your account accepts legacy credentials ("username and password") or IAM tokens.
See https://cloud.ibm.com/docs/services/Cloudant/guides?topic=cloudant-ibm-cloud-identity-and-access-management-iam-#ibm-cloud-identity-and-access-management-iam-

Android php insert record prevent DOS attack and csrf attack in multiple submit

I am new to android development .I have developed an android app from where one can insert some record via the app to the mysql database using php as server side programming.
No need to perform any kind of login operation for inserting the record via the app.
So now the problem is that if a user clicks on sumbit button multiple times(say x times) within a fraction of seconds, then same record will be inserted into the database multiple times(x times) ..obviously with different primary key id in each row.
So i need to prevent it by generating a unique token in oncreate() and pass the token along with the body post request and validate it at the server end using php.
The token must be unique for each post request via app to the server and also it has to be destroyed once it is used for a particular request.
So how to go for it? Please help..i need a reference code if anyone can provide..
A lightweight approach is to generate a token that can self-validate using an HMAC. On the server, you'd generate a token using say generate_token($secret) and send this to the client. The client has to include the token in it's response. Validate the token on the server with valid_token($secret, $token).
To prevent re-use of tokens, you have to store the spent tokens. For example, you could store used tokens in a db-record with a unique constraint before proceeding with the request. If inserting fails on the constraint, you know the token was re-used.
Example of token generation and validation:
function generate_token($secret) {
return build_token($secret, bin2hex(random_bytes(5)));
}
function build_token($secret, $id) {
return $id . '-' . hash_hmac('ripemd160', $id, $secret);
}
function valid_token($secret, $token) {
$parts = explode('-', $token);
return $token === build_token($secret, $parts[0]);
}
There are other ways. You could generate random ID and store them. Then delete them from the store once they're used. Then you don't need a secret. I prefer storing spent tokens because it's stateless up until the last step.
Edit: Note that to protect against CSRF the token has to include a user-specific ID. In PHP, session_id() can often be used for this. A very simplistic approach would concat session_id() to $secret as in generate_token($secret . session_id()) and valid_token($secret . session_id(), $token). I hope you get the idea.

What to do with the token data when the user signs out from android app?

The questions is pretty simple.I am also a novice regarding token authentication.
I know that, in case of token authentication, in case of android apps, token is used so that the user credentials does not remain in the app.i.e. whenever the user fetches data from server, it does not send the user credentials everytime but he sends token.
When the user signs in for the first time, from the app, a token is generated from the server and is "entried" in the database beside the user data.This token is send back to the app from the server and it is this token that the user, from the app, has to send everytime it plans to fetch some data from the server.When the user has to fetch data, it sends the required parameters and with them the token.This token is matched with all the tokens present in the database.If the token is present,it also gets the user associated with that token.And as the token is present so the user session is valid and then the required data from the server is send back to the android app.
What i want to know is that what to do with the token, in both client and server side, when the user logs out?
If any doubt please comment.I know its a simple question but dont know much about token authentication.Thanks everyone for their time.
Note:- Also if any of my concepts, in the question, is wrong please feel free to correct me.
Basically all tokens have an expiry. This is intended for security purposes. But you can choose whether to set an expiry for your token. But I suggest that you must put an expiry for your token. And also delete that tokens from both server and client, and set user session to login again. Use timestamps to create the tokens. They are also useful when comparing tokens.
Happy Coding.... :-)

How can I avoid many request to my server (PHP-Java)?

I am developing an app for Android which allow users making comments. The problem is: if someone discovered the PHP file of my server which receive a comment and save it in a database this person would have a total control to save unlimited comments. So... How could I avoid this?
I don't know so much of security but... Could it be possible solve it with hash, keys or anything? How?
You could use Oauth and send a token with each request here a example link Oauth2 or you can use a more simple method like:
User log in you app then you create in a table a record with is id and random string
Return this string to the user
When user do request add this string
On PHP verify thata string exists and the id is correct then insert the comment else nothing

Best Practice Using JSON to pass data from Java to PHP and PHP to Java Securely

I have been working on an android application project that uses HTTP Get to send and receive data from MySQL through a PHP file using JSON from Java.
I have lately been running into some issues in theory behind best practices using HTTP Transport and passing Parameters via a URL.
First Question:
How should I be passing my data to my PHP Webservices ?
Currently I am just passing the data through single parameters using key value pairs like so:
myurl.com/retrieveinfo.php?user_id=453&password=sha1-hash-value
Should I be moving this type of request to append a JSON object onto the URL instead? like so:
myurl.com/retrieveinfo.php?{\"users\":{\"username\":\"User1Name\" ,\"user_id\":453 , \"password\":\"sha1-hash-value\"}}
Second Question:
*How should I be handling the JSON Response from the Server ? Do I need to push this work off to a handler and make sure the UI Thread is not the one doing this work? *
Currently I am just parsing the JSON using separate methods for each Object Type such as
User.Class
private void parseUserInfo(JSONObject response){
// Do all my Parsing for a User Object
try{
JSONArray users = response.getJSONArray("users");
JSONObject user = users.getJSONObject(0);
// Get the User info etc...
}catch(JSONException ex){
ex.printStackTrace();
}
}
Notes.Class
private void parseNotes(JSONObject response){
// Do all my Parsing for a Note Object
try{
JSONArray notes = response.getJSONArray("notes");
for (int index = 0; index < notes.length() ; index++)
{
JSONObject note = notes.getJSONObject(index);
// Get all the note info etc...
}
}catch(JSONException ex){
ex.printStackTrace();
}
}
Third Question:
I would like my PHP server files to only work for my Application. So what is the best way to secure my PHP files on my server so a request to my files wont go through if its run in a browser ?
Should I be sending some temp key that only my application knows about ?
Thanks
First Question:
You don't really want to put a JSON object on the url as a query parameter. The real two debates that I see is that you either 1) use the key value pairs you were using, or 2) make this a POST and send the JSON as a payload.
Since you are not planning on exposing the API to anyone, I don't really find it important for you to follow standard nomenclatures. Do whatever you want to do. However, from a REST standpoint, anything that retrieves info should be a GET call, and the data should be key-value pairs on the query string. However, it looks like you are passing in a username and password (ok, the sha of the pass). It is considered best practice to always pass user info as the payload. So almost all login type protocols use a POST for user data. User-id's or session id's are common in the query string but usernames and passwords should almost always be in a payload.
Note: sometimes in TLS (SSL) it is considered ok to include these things in the query string.
Second Question:
Honestly, I would just use Jackson. https://github.com/FasterXML/jackson
But otherwise, it is normal to have a seperate layer for parsing. In otherwords, one class handles all the parsing. You do not want to put this code inside your models if you can avoid it. The new layer would handle parsing and would pass the Java Model objects down to the next layer.
Third Question:
The easiest way to do this would simply be to check the user-agent header on the request. Make sure that the user-agent is your application, and not a browser.
However, it would still be possible for people to "spoof" this. Using a temp key wouldn't really help either, because once people sniff the traffic they can figure out the temp key.
The standard thing here is to do some type of session based key, where the application sends some type of MAC in order to prove it is a valid client.
You could also consider using OAUTH2 to protect your api's.

Categories

Resources