Access database securely from iOS App - php

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.

Related

2-part confusion with slim restful backend and twig

I am building an app to better understand Restful back-ends with clients that makes calls to it. I am using slim to handle routing and service calls. I am stuck on two things though.
Part 1 - If restful APIs should not use sessions how do I keep information like authenticated and user_id available? It was my understanding storing that information in a cookie was a bad practice. Once a user authenticated normally I would use $_SESSION['uid'].
Part 2 - This part is more confusing to me. I am using Twig for front-end (not a cool js guy). Doing so all on the same server I use slim-view to render twig. But that means my back-end is not sending JSON it is doing everything. How is something like this separated? Is it worth while?
Part one
One method is create a dynamic API key that is temporary, with this temp key you can then authenticate and authorize any request coming from the client.
On the server side you can store this temp API key inside a table with some fields to keep track when the key was last used and how long the key is valid. By doing this you can invalidate API keys at the server side
The client can store the key wherever but if you are going to use PHP then I suggest storing it in the session
sidenote: This answer is based on an API I worked on. The field static in the table api_key is used for keys that only can be used to login an user and obtain a dynamic key that then was used for authentication and authorization.
This was due to the fact that our client was written in JS and the static API key was plain visible in the source code.
So the client first had to issue a login request before obtaining a "legit" api key
part 2
You need to decouple your client project from you server project. Your client should only ever receive data (e.g. JSON) from the server, your server should never worry about how to present the data only about sending it the client.
The client can be written in any language and can even be hosted somewhere else. The only thing a client can't do is contact the database directly. It has to request every piece of information straight from the server

ASP.NET authentication for custom API

I know this is a pretty discussed topic but i'm struggling in finding a solution for my case.
I have done an already working API service in ASP.NET (c# 4.5.1). My clients uses php pages to call a page.aspx on my server and sending via POST a string. This string contains an ID and a cypher message. Every user have a different key (AES 256) and, since i have the ID i get from my DB the correct key to decypher the message and do what its request contains. I also check the IP, every client have only a list of approved IPs (when they are not using the debug mode for testing)
I like this method but now i have to let my users do some purchases. I already implemented it (thank you PayPal) and it works, but i feel my security weak.
So i wanted to add some already known and already wrapped authentication system, without re-writing any of the already working and debugged code.
Since is used from lot of big internet services i thought about OAuth 2.0 (and i know nothing about it), but looks like everyone who talks about it is for creating a login that uses services like Facebook, Google, Twitter and go on.. not my case. I have my own database with my user list and i need to know with 100% security who is calling my API service.
I tried creating a new Web API 2 project (MVC.. damn) but i cannot understand if i can use for my service without rewriting the logic for API calling (and from what i saw looks like no is the answer)
So the question is: What authentication method can i use that is easy to implement without rewriting the already working code and can be usable from clients with PHP?
I was watching "ASP.NET MVC 5 Fundamentals" tutorial on Pluralsight by Scott Allen where he explains it quite nicely. But before watching that tutorial, for one App I worked on, we had a table in the database with tokens that were issues at Login. Then the client would send the token with their request. At server side, I did a custom attribute called [CheckToken] inside which I would check if the token exists in the database and if it is stil valid (not expired, etc.) I went a step further and sometimes swap the token so that even if the token gets stolen, it would not be valid for long. That way, the user does not have to keep login in all the time.

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.

Categories