How should an API on the same host be implemented through PHP - 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.

Related

Safely connecting to Cloudant using AngularJS (and possibly 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

How to securely connect to a web api from a AngularJS site

Being relatively new to web development, at least using client side technologies such as the AngularJS framework, I need to resolve a few queries before I can start my latest project.
I am writing an application using the AngularJS which reads/writes/updates data in a database. With javascript being client side I have chosen to write a PHP REST API to do the database queries, resulting in a secure username and password and a single database layer.
My question is, given my REST API, I will be using AJAX from javascript (which is client side) to invoke methods. How do I stop other sites from writing a script to invoke the REST API as well? Putting an authentication token in the javascript code isn't very secure, someone can just copy it.
Is a REST API the best approach for this problem? I am not adverse to learning new technologies or practices so please, any thoughts on better design patterns or methods of implementation are greatly appreciated. Unfortunately, due to my limited domain knowledge in this area, I have been unfruitful in my Google Searches as I'm not confident of the terms under which I should be searching.
Many thanks.
Since your Angular application is living in the browser, your REST API will need to be publicly accessible from any random visitor's browser. You thereby have a public API, out of necessity. You can't restrict it; either visitors can see the data or they can't.
Essentially this is not significantly different from a traditional webpage though. In a server-side generated page, you output your data packaged as HTML and deliver it to anyone who asks. In a REST-API/Angular app, you deliver the data packaged as JSON to anyone who asks. Either way the data is equally public, though maybe the REST API is a little easier to "abuse" than scraping the HTML would be. It may be useful to deliberate employing some user behaviour tracking and throttling, if you want to avoid someone outright sucking all of your database dry; this applies equally to JSON based REST APIs as it does to regular web pages.
If you're also exposing read/write APIs this way, you're of course wide open to abuse.
The only way to make an API non-public is to require password authentication. If the users of your site must be logged in, then you can restrict the API to anyone with a valid session. This doesn't help much in the grant scheme of things if anyone can simply register an account on your site, but it needs more deliberation and provides slightly more manageability than a completely open API.
Admin-only APIs of course must be protected in this way, requiring an account which only you have the credentials to.

Hot to use the Basic Auth for REST systems with client in browser? [duplicate]

Being relatively new to web development, at least using client side technologies such as the AngularJS framework, I need to resolve a few queries before I can start my latest project.
I am writing an application using the AngularJS which reads/writes/updates data in a database. With javascript being client side I have chosen to write a PHP REST API to do the database queries, resulting in a secure username and password and a single database layer.
My question is, given my REST API, I will be using AJAX from javascript (which is client side) to invoke methods. How do I stop other sites from writing a script to invoke the REST API as well? Putting an authentication token in the javascript code isn't very secure, someone can just copy it.
Is a REST API the best approach for this problem? I am not adverse to learning new technologies or practices so please, any thoughts on better design patterns or methods of implementation are greatly appreciated. Unfortunately, due to my limited domain knowledge in this area, I have been unfruitful in my Google Searches as I'm not confident of the terms under which I should be searching.
Many thanks.
Since your Angular application is living in the browser, your REST API will need to be publicly accessible from any random visitor's browser. You thereby have a public API, out of necessity. You can't restrict it; either visitors can see the data or they can't.
Essentially this is not significantly different from a traditional webpage though. In a server-side generated page, you output your data packaged as HTML and deliver it to anyone who asks. In a REST-API/Angular app, you deliver the data packaged as JSON to anyone who asks. Either way the data is equally public, though maybe the REST API is a little easier to "abuse" than scraping the HTML would be. It may be useful to deliberate employing some user behaviour tracking and throttling, if you want to avoid someone outright sucking all of your database dry; this applies equally to JSON based REST APIs as it does to regular web pages.
If you're also exposing read/write APIs this way, you're of course wide open to abuse.
The only way to make an API non-public is to require password authentication. If the users of your site must be logged in, then you can restrict the API to anyone with a valid session. This doesn't help much in the grant scheme of things if anyone can simply register an account on your site, but it needs more deliberation and provides slightly more manageability than a completely open API.
Admin-only APIs of course must be protected in this way, requiring an account which only you have the credentials to.

Restful App making SAFE CRUD requests to the server using php laravel

Question may sound similar to a lot of information thats under Resful Designs.
I've read numbers of articles went through bunch of tutorials, trying to understand how Resful apps work. I see bunch of tuts. Looked into OAuth but it is not what i need..
Since security is my main concern, I have come to problem of how i should be handling nonces/hashes!??
What do i mean by nonce/hashes is;
I have a Restful application which uses laravel 4.1. Framework, users can log in with Auth::User() implementation. All is good. ALL REQUESTS I make to the application are CRUD.
Why Do I want to use nonces/hash;
Lets i have #DELETE Route("workouts/{id}") under api prefix in my resource
users can delete workouts using example.com/api/workouts/1 does it not has to have also something like {nonce} attached to the link like example.com/api/workouts/1/nonce/12321321313 since everyother user may fake redirect user and make a person delete its own workout?
Most of the Articles indicates that;
As far as I know for security concerns, I should be sending a nonce along with every ajax request to the server, then server must verify and respond back to the client with informations along with new nonce for the next request? This is a performance killer but is it the way?
HTTPS REQUESTS?? NO TOKENS/hashes or nonces?
So some say Under HTTPS PROTOCOL after logging in safely(valid credentials) there is no need to send a nonce ( to the server) for each request (such as CRUD) anymore. Authentication with credentials is enough to authenticate user for goods.
Looking Through all of Laravel angular tutorials
There is nothing mentioned about using tokens nonces or anything at all, at least not that I've seen of.
My main question is how I should be designing server side routes to make safer requests to the server with laravel using tokens, nonces or hashes etc?
I know there lots of topics but they seem very theoric to me. I dont know which are accuratly protective and which arent. So thank you for your patience of reading it and hope to gets some accurate response..
and excuse my English :)..
I believe that using the term RESTful application is a bit misleading. But, if you using a REST API you should have a look at JSON Web Token for authenticating users to your API.
Some helpful links here: JSON Web Token, and a Laravel package jwt-auth and an Angular example, keep in mind that the Angular example is with Node.Js but it can be integrated with Laravel.
If you are using just AJAX requests to PHP scripts for CRUD why not use a package for protecting against CSRF attacks for Laravel, just google it and you find more tutorials.

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.

Categories