Safely connecting to Cloudant using AngularJS (and possibly PHP) - php

I built a very simple AngularJS Shop App that creates product orders.
As of now, the app just sends orders via email to the customer and retailer using PHP, but I thought it might be good to learn a bit how to use databases, and store/retrieve this orders (which are arrays) into a Cloudant.
But then I realized that to connect to the Cloudant service, the call looks like this:
https://{username}:{password}#username.cloudant.com/DB
I assume this is not very safe at all, as the call and credentials would be visible for anyone.
Also, in the App there's no need at all for anyone to have an account or login, which would partially help with security.
As I have 0 experience with Node or any other backend system, I'm wondering: Is it possible to make secure calls to a Cloudant service using only AngularJS (or PHP to store the sensitive values)?
I've read a bit about the one db per user, but it doesn't seem to help in my case, where I need one single DB to store all my orders.
Any tips would be highly appreciated.

If you need to expose your credentials in your API calls, you better not do them from the front-end. If you're using Angular and PHP, the easiest way to hide your auth info from the public would be the following:
Create a PHP file and move your API code to the back-end.
This will be a bit of work, but in the end the service login should happen on the server. This file should receive requests from the client and transmit them to the remote service, then return its response to the client.
Use AJAX on the front-end to make calls to the above PHP file, and proceed displaying its response to the user like you would handle an API response.
This way your API credentials aren't exposed to anyone checking your page's HTML source and you can keep most of your front-end logic the way you have it set up already.

As #ppajer said, I strongly discourage to use AngularJS to do what you want to do. Leave it on the back-end and use ajax to make the calls. Take a look at this repo, it may help you: https://github.com/osipov/bluemix-cloudant-php-sample

Related

How should an API on the same host be implemented through PHP

I have tried googling for related topics for this but was unable to find anything that answered my question so here I am.
I am going to be building a REST API for my web based application to improve scalability and allow me to easily implement site updates and build other applications. However, in my research I have not been able to figure out a way to use this API within PHP itself. As it currently stands, the API will not be public and will be hosted on the same server as the website hence my question.
The website currently uses PHP to load in content server side and then JavaScript to dynamically add content and embellish the user experience. I would like to keep it this way but have all requests including PHP ones to go through the API. Obviously the JavaScript will use an HTTP request going to a specific endpoint e.g "htp://example.com/user/123" but it seems cumbersome to do the same process using curl with PHP when the API is on the same host.
If I understand correctly removing the HTTP request from the mix will mean that it is not restfull but that is not an issue. So:
1: How should I make calls to the API from PHP?
2: How should I maintain the user session? Bearing in mind that the session should not be maintained by the API and JavaScript will send all neccesary data for authentication with the API call.
Use Zend HTTP Rest Client - it is having powerful rest architecture
Yes - you are right, you cannot maintain sessions when using API, so try to use another way for maintaining authorization like create some class which will check your authorization based on the API response
Use some kind of token which is unique for each user and pass it with header authorization.

Access database securely from iOS App

I chose MySQL after looking between MySQL and SQLite for accessing because my iPhone app needs to pull information from an online database that is already in MySQL.
I believe the traditional way of accessing information would be: To have a php file on the server that does the accessing for you.
The iPhone app would call this php file and it would return the results.
iOS app will call http://somewebsite.com/index.php?id=234 and the website would print out the username of id=234.
Now, how secure is this process?... I would obviously use prepared statements and https. But what if someone found the URL for this website? How do I protect myself against misuse (someone could generate a list of all my users)? Is this the standard way to have your iPhone app connect and get info from a database?
Edit: Furthermore, lets say I needed to create an app login page... I have a MySQL database with username and password (hashed obviously). Would it be safe to use $_GET variables to see if they are authenticated. Like for example: https://somewebsite.com/checkauth.php?username=test&password=C3LyiJvTCQ14Q and have the php print out yes or no. Picture examples below:
I would assume the above method would not be safe to do... but I need to be enlightened.
Also, I'd prefer to stay away from calling the database within the app using third party API, not supported by Apple.
The best way to go about this would to setup an API to interact with the database on the server and your iPhone app just queries the API and returns the data in a machine readable format such as JSON, see http://en.wikipedia.org/wiki/JSON and http://json.org/. So for user login the server would return maybe something like:
{
"result": false,
"error": "Invalid username or password"
}
This would be generated by PHP with the following code:
echo json_encode(array(
"result" => false,
"error" => "Invalid username or password"
));
Also note that, you should use HTTP response codes in conjunction with this, eg 401 for unauthorised.
JSON can use boolean and other data structures within its format. Nearly all major languages have support/libraries for it.
The benefits of this is that it allows you to build other applications using the same API such as an android version or an actual website.
This SO question is a good starting point on the security of mobile applications:
Creating an API for mobile applications - Authentication and Authorization
The main points are make sure to use HTTPS. When sending over user credentials you could return a user token (api key) that can be used for future requests and stored within the iPhone app for future access.
Eg: https://iphoneapp.com/notifications.json?key=98fy92473r92hAAIYEFG397qbqwiuUEAF
Your key should be sent in a HTTP header or in the POST so it is not recorded in logs etc...
Note: This is just a random string typed on the keyboard.
This method allows you to delete/regenerate the key if it gets compromised. You can also set rate limiting on the keys and various other parameters.
Another huge benefit is by building an API that your own app uses means that it will be maintained to a high standard and other third party companies can also use the API (if you allow them).
Edit: Furthermore, lets say I needed to create an app login page... I
have a MySQL database with username and password (hashed obviously).
Would it be safe to use $_GET variables to see if they are
authenticated. Like for example:
https://somewebsite.com/checkauth.php?username=test&password=C3LyiJvTCQ14Q
You should send that sensitive data using POST instead, but any service has to login at some point. Using HTTPS should help the most as it prevents eavesdropping. After the first authentication you can return the token and reap the benefits mentioned above.
As for the user login as along as your PHP conforms to good practices you should have no issues. See http://www.phptherightway.com/ it will help a lot if you have questions.
Definitely research OAuth and utilize that if you can/want to.
This is just a starting point and is NOT meant to be used word for word, further reading and googling is required.
If you're looking for an alternative to a "build an API from scratch" approach we've used a web based service called Kumulos available at kumulos.com for a quick and easy solution.
This service allows a developer to connect to a MySQL database and build the data model and APIs via a web page then deploy a native library to your platform. I believe you can also import an existing data model as well.
Once the data model is built on the web page you can then build APIs and specify input and output parameters. The APIs are modeled based on the type of SQL operation you are performing such as SELECT, UPDATE, INSERT, DELETE.
In your case you would want to model a login/authentication UI which accepts the username and (hashed) password, validates the data against the Users table and return the authentication results.
Once your APIs are modeled via the web page you can then "deploy" your configuration and generate native libraries for iOS, Android, PHP, and others.
The generated Obj C library gets dropped into your project and you make and respond to APIs using objective c calls and delegates.
Kumulos includes some other features as well like data export, API call metering, and what they call KScript. This is essentially the ability to wrap your call in javascript at the server (also configured via the web page) to greatly expand the flexibility and capability of the API call functionality you can build.
We've had a couple of questions or support issues over the past few months and their support has been top notch. Their backbone is on Rackspace. We've got about 8 or 10 production apps running APIs through them at the moment and are quite satisfied not having to hire an API developer :)
Many mobile applications use APIs to get and store information in servers. Figuring out some of these endpoints is not complicated, and having unsecured endpoints returning sensitive information is a dangerous thing to do.
The first level of protection of your API could be to create an "API key" that identifies the application. This key is stored it in the server and checked on every request. Request with no API key should return a HTTP 401 (Unauthorized) status code.
API keys are okay, but insufficient when some calls can only be performed by certain users. For example a user needs to update his information, only the owner of the information should be able to perform this call, and not another user. For this you can pass authentication information that identifies the user to perform the update action.
I do not recommend using username/password on every request, instead have the user authenticate once, and let the server send back authentication tokens that can be used by the application to perform future authenticated calls. Take a look at OAuth2 as a potential Authorization Framework. Also check out OAuth 2.0 - The Good, the Bad & the Ugly.
I suggest using BShaffer OAuth2 Server in PHP. Also see Best Practices for securing a REST API / web service for alternatives.
From your question it sounds like there is an existing subsystem, I recommend creating a simple interface that makes the subsystem easier to use, and reusable across multiple clients instead of modifying the subsystem to accommodate an API. This is commonly known as a Facade Design Pattern.
Many PHP Frameworks have packages to implement custom RESTlike APIs. Symfony has FOSRestBundle, FuelPHP has a REST controller out of the box and CodeIgniter has a REST server.
To summarize:
Create a simple interface to access information from the existing system (a REST API).
Protect your private information using a proper authentication mechanism (maybe OAuth2).
Use existing libraries and/or frameworks to speedup development.
Your code will be reusable across multiple applications and platforms as a result!
if you want to access database from IOS Application and save data into database you have to use middleware solutio.
which is Webservice
Create Web Server In Microsoft ASP dot Net And Access That WebService in IOS Application With that you can communicate between two different OS.
return from Webservice is XMLdoucment which can be further parse with xml purser.

most secure way to "call" a php file

I am creating an app for my clients to add to their webpages. however, I am hosting the database that stores the info for this app. All I want to do is do all the queries on my server and somehow pass the $var to their server.
so what I was thinking was to have my PHP page with all the MYSQL credentials store on my server and give them a code that calls that page and outputs the stuff, something like
require_once('192.163.163.163/config.php');
But I bet this is the least secure way to do this. I don't want to give anyone access to the central database and I am handling all the requests. Do you guys have any suggestions that I can pull the data off my db and pass it to their server in a $var without opening any doors?
If you can't afford to give away your DB credentials or other internal details of your system but you need the clients to be able to read data from you, then the only really secure way to do set your system up as an API that the clients can call.
Don't try to combine the two systems into a single app; it will open up holes that cannot be closed.
To create an API is fairly simple in principle. Just create a suite of normal PHP programs that accept a set of pre-defined arguments return the data in a pre-defined format that can be easily processed by the calling program -- eg maybe a JSON structure.
The clients would then simply call your system via an HTTP call. They'd never need to see your code; the wouldn't need to be hosted on the same server, and they wouldn't even need to be writing their system in the same language as yours.
There's a lot more to it than that -- it is, of course, perfectly easy to write an insecure API as well, and you'll want to read up on how to write a good API to avoid that sort of thing -- but that's your starting point. I hope it helps.

Need help to figure out how to do a remote API connect call on my site

I have some skills in PHP and now I'm planning to develop a connect function for remote login to my web side. I can't find any useful on Google.
Some idees on how to code a API connect button? Something similiar to Facebook connect, Twitter connect etc. BUT this should not rely on facebook api. I'm going to make my own stand alone api.
I know I need to use REST in backend, but I'm missing the knowledge to know how to send / recive the login data, and how to know when a user are online or not.
I also know that the user will need a key of some sort.
My plan was something so easy as this:
yourdomain.com/api?id=xx&key=xxx&what=
then what is should be the action with som parameters like:
if($what == login) {
handle the login part here
return the data
}
I can handle the php on the server side, but don't have a clue on how to handle the rest except the remote site must get the data in json or xml format and save in database.
Then when connect, it sends some data back to my site.
But HOW?? Here I'm stuck.
Also how to figure out when user are online on the other site or not, and how to get the image for a button. Like Facebook have a blue icon.
I guess it's a call back to my site for getting the image from there, right?
Greatfull for any answers on this one.
Its a pretty large topic you have there, you'll need to do some research as there are many many ways and technologies and security aspects related to this.
I'd suggest you go with a secure connection on a SOAP service based off Zend Soap Server and Zend Soap Client. But then again, if you don't want to use ZEND or SOAP, you'll have to look at other methods.
I wouldnt use REST because REST is used to manage data such as PUT/POST = UPDATE/INSERT, DELETE = DELETE, GET = SELECT so i don't really recon this would make sense.
My biggest point i have to make is, MAKE APIS, something simple, you don't want people to have to ask you for help or read documentation on how to access your authentication service. Go something simple, clean, portable and provide API to simplify your user's experience.
My 2 cents :P

How to create a React Native login with PHP and consisting login session?

I'm about to start a new project with React Native to create an app. Coming from web development (mainly PHP, SQL), I'm wondering about how to create a login session in the app.
While, on the web, you've a session on the web server and a cookie stored locally - what do you use then for a React Native app, also providing security with that?
I think one may use an API for that to validate user data with a POST request, but then afterwards I'm asking myself how to create a persistent and secure session?
I hope you understand what I mean. Does somebody has an example for that or a type of simple "flow-chart" to help me understand and/or finding a way how to do this?
Thanks
React Native use something similar to session. It uses async storage to store something like a cookie when the user is log in and will check if the "cookie" is still valid while opening the app.
I let you have a look on redux-react-native-session.
There is also all made API like Firebase where you just have to make call to their API's functions to log in, disconnect, ...

Categories