Carry data from start of authentication process to end of process - php

I am developing a Google Marketplace App. I am using PHP.
I am trying to have an access point to my app which doesn't require the user to have logged into my app (or possibly even Google Apps for that matter), and then once they have submitted the entry point (which just consists of a string) that string is carried through the authentication process so that when they authenticated my app can process that string just as if they had been logged in.
Basically I have a HTML form which is like a cut down version of my app (which can be embedded on a website using an iFrame for example), and when the user fills it out it does an AJAX call to an API in my app which does require authentication, so the authentication process begins, but once it has finished it has lost the original data.
Does anyone know a solution to this?

I am not sure that you need to use Sessions for this - might be overkill. I am not sure the exact specifics of your application, but you might be able to place the data in the $GLOBALS superglobal. Take a look at the documentation:
php.net/manual/en/reserved.variables.globals.php

I ended up using sessions however it was more tricky than usual because the authentication occurs on a different domain to the access point to the app. What I ended up doing was encoding $_SESSION and storing it in a database, and then when the authentication has occured and the app is logged in it checks the database for any sessions and restores them.

Related

Securing the token of a token based authentication system

I am using a token based authentication for accessing a few crude web APIs I have designed for my site. At login, the username and password are posted to the login API, and it generates a token with a unique secret key, and the key is stored on the database. At each subsequent call, the token is sent with the request and verified on the server with the secret key.
I am using a web app to consume this API service and deliver a front end to the users. The web application is designed using HTML/Bootstrap/JQuery and the backend is written on php.
I have successfully tested my app and the token based authentication works. However, I have one concern. I find that the user id and token are displayed directly, only using url encoding on the address bar of the browser.
http://hasconpanel.ckoysolutions.com/hasconpanel.php?inputs={%20%22username%22%20:%20%22Debopam%20Parua%22%20,%20%22uid%22%20:%20%2220170520193421DP%22%20,%20%22token%22%20:%20%22Sa2pHyooWPoI79vfvJzLlw7UO%252B2p5hOpBttkEq7LQ%252BjAGm9XEmxfhLAcnJoLbqrsXCp75%252BG1M7nEUoCgsDVbIQ%253D%253D%22%20,%20%22list_of_devices%22%20:%20[{%22device_code%22:%22b8:27:eb:f1:b3:0f%22,%22device_name%22:%22First-Pi%22}]%20}
Now, if this address is copied, or suppose the browser is made to resume the previous session, no matter who tries to access it, they get an entry. Especially in case of public computer centers, if anyone accesses my web app with their credentials, and forgets to logout before killing the browser, the token system seems to fail miserably. Is there anyway to secure the token like encrypting it? Or someway for the app to not store the parameters in case of a browser/browser-tab close or at least not display it on the address bar? I have thought of making a fresh token at each request, but it slows the system drastically, so I want to avoid it.
Please suggest some way to solve this problem.
Thanks in advance.
Edit:
Explaining how the system works now:
The api system is hosted on the main domain of a shared server, and the app is hosted in a sub-domain. The main domain also hosts several webservices that are being called from a few raspberry pis installed at home.
This is how it works, the login is made from the primary website and on successful login, the web app is called with a get call with the user id, the token and a list of working devices for the user. Check is provided to prevent the app page being accessed without any of these three parameters. On fresh load, the user gets the choice to select a device from a drop-down menu. Now, each of these working devices can have three separate systems running. So, on selecting the device, a get call is again being made to the app, with the selected device added as a parameter along with the three previous parameters. This shows the token and the uid on the address-bar.
Token based authentication is very standard in the web world. The details vary, but what you are trying to do certainly isn't crazy. However, your security concerns are valid, and there are a number of potential solutions:
Use HTTPS exclusively. This will protect your token from being easily readable by everyone in between the user and you. Actually, do this regardless of anything else. HTTPS should be considered the default for security purposes these days: just pretend that HTTP is deprecated.
Move the token into the header of the request instead of the URL. As long as you are using HTTPS this doesn't actually change anything from a security standpoint, but it is fairly standard for the industry. It will also keep the token out of the browser history.
It is strange that you have a URL showing up in the browser address bar. I would expect a client-side application to make requests exclusively via ajax, which means there should't ever be anything in the address bar. You might need to clarify more on how exactly this application is working. I suspect you need to refactor so that none of your application URLs ever end up in the address bar, and instead operate via AJAX requests exclusively.
Still, HTTPS is the most important part. Your entire transaction after DNS lookup will be transmitted securely, so the token cannot be stolen by a man-in-the-middle. This is the most important step you have to take to secure it. If you don't use HTTPS, you might as well broadcast it to the world. Of course, if you are making non-ajax requests to a URL with the token in the query parameters then the token will be visible in the browser's address bar and history. Again, avoid that by using ajax requests only and put the cookie in the header.
Once you have HTTPS in place with ajax-only requests, the chances of having a token stolen are much smaller. Still, it can happen (in particular via an XSS attack), so become familiar with the principle of "defense in depth". Also, there are steps you can take to try to detect a stolen token an invalidate it. Things like:
Invalidate a token (for the user to log back in) if the IP Address changes (although this can impact mobile users, which probably isn't desirable)
Invalidate a token if the user agent changes (although that can be spoofed)
Enforce a server-side maximum session length
Make sure and require the user to re-authenticate if they want to change email/password.
Those are just a few suggestions off the top of my head. Again though, this is a pretty standard problem, so google will be your friend.

Allow only PHP request from Android App

I have some PHP pages that receive POST requests and make CRUD operations in my MySQL database...
I would like to know if there is a way to allow only my Android application to do those requests in my pages...
As my application requires Google Login (which Google IDs are already registered in my database), I was thinking in check if client's Google ID exists on database via PHP script, but it could be faked, right?
Is there any other way to allow only my Android App to make CRUD in my database? Maybe using another language beside PHP
Thanks in advance
I would like to know if there is a way to allow only my Android application to do those requests in my pages...
This is an impossible request.
You cannot guarantee that end users are using your application to send data to your server over a public network (i.e. the Internet). Full stop, not gonna happen.
What you should do instead is ensure your server-side code is written to where, regardless of what data is hurled at it, your server doesn't get hacked.
I would store a secret key in your app and send that along with the request to log the user in. This secret key would be stored on the server and compared at login. If the key matches and user is authenticated then log user in.

Mobile App: users writing to DB how to be sure they can(authentication)?

I think it's important to say that I don't have any experience in the technologies nominated below, I have some idea what is going on, I've googled a lot, but still - more I google more dumb I feel. :)
Making an app in Ionic 2, users of this app can read/write data about themself in DB.
I am using Wordpress as backend, actually users will change values in the table that was created by some Wordpress plugin.
First problem - I have no experience at all.
Second one - I must understand which user is knocking to the server.
Because user can change only his own data in DB.
I've solved it by creating a script that checks GET request from app & that request has a param with user nickname, so I have turned this script to template and assignined it to the page. ( template was first thing that went to my mind, if you have better idea - please tell me how to do it better! ).
Well now I knew who it is, but I disliked that this so unsecure!
Its only GET request with user name in it and changes to bring into DB.
NOT GOOD.
I've thought that I should send not only nickname but also some kind of a password, so I can check if the user is actually genuine user, well, you know.
But knowing nothing about security, didn't know where to start so I've started googling.
I've find out that there is 'Basic Authentication' - disliked it because password is verry simple to decode (base64) and you must send it with every request (not safe).
Then I thought about crypting pass with strong algorithm like bcrypt & then send it with the request. Disliked it too - because at the end you are always send a password even if strongly crypted.
Now I've started to look in the direction of Auth 1.0
(because saw that wordpress has a plugin for it, I know little about wp however).
But after all I am not so sure that I am doing things in the right way.
I must finish many things, but I am stuck with this security issue and I don't know if it's my paranoia and there is simplier ways to accomplish what I want to do.
Don't have much time, don't want to waste time anymore.
Please, someone who is pro in this stuff give me an advise how to do this thing in the right way!
because I am going crazy with that stuff.
The best practice is to issue an access token from your server to your (or even third-party) client application by the following steps.
A user uses a client application.
The client application asks the user whether to use your service.
The user answers "yes".
The client application opens the authorization page of your service using a web browser. In other words, the client application makes an authorization request to your authorization server.
The authorization page explains to the user that the client application is requesting some permissions and asks the user whether to approve it or not.
The user inputs his/her ID and password into the login form in the authorization page and then presses the "approve" button.
Your authorization server authenticates the user and issues an access token to the client application.
The client application accesses a Web API of your service with the access token.
The Web API of your service checks whether the presented access token is valid or not.
If the access token is valid, the Web API returns a successful response to the client application.
RFC 6749 (The OAuth 2.0 Authorization Framework) defines 4 flows to issue an access token. Check the specification.

Php pages let connect only to android application [duplicate]

I have some PHP pages that receive POST requests and make CRUD operations in my MySQL database...
I would like to know if there is a way to allow only my Android application to do those requests in my pages...
As my application requires Google Login (which Google IDs are already registered in my database), I was thinking in check if client's Google ID exists on database via PHP script, but it could be faked, right?
Is there any other way to allow only my Android App to make CRUD in my database? Maybe using another language beside PHP
Thanks in advance
I would like to know if there is a way to allow only my Android application to do those requests in my pages...
This is an impossible request.
You cannot guarantee that end users are using your application to send data to your server over a public network (i.e. the Internet). Full stop, not gonna happen.
What you should do instead is ensure your server-side code is written to where, regardless of what data is hurled at it, your server doesn't get hacked.
I would store a secret key in your app and send that along with the request to log the user in. This secret key would be stored on the server and compared at login. If the key matches and user is authenticated then log user in.

Facebook Authentication Implementation

I'm working on a project which will use facebook authentication completely (no custom authentication implementation exists). Project uses PHP for server-side scripting. I looked around for implementing fast and secure authentication mechanism but i cannot find any detailed description about this subject. Facebook's documents are weak and does only provide basic information.
Which authentication method would be appropriate? There's a Javascript SDK and PHP SDK. As i understand, i have to use Javascript SDK for login, then using PHP SDK i will check my database for verifying credentials. But using Graph API with PHP SDK is slow. Is there a better way to validate session?
Will i need to check session server-side (PHP-SDK) on every request?
What I end up doing for my apps is pretty simple and relatively fast compared to any other method I've seen.
Check the signed_request if exists, parse it if it does. If it doesn't, set the $login flag to 1 in PHP
I check the user's session / cookie to see if the user was previously authenticated by the app (will come back to this later. If it is empty, set $login to 1.
If the login flag is set to 1, send the user to the installation url.
The user installs the app and is sent to a connector page. This page serves the purpose of getting an access_token and generating a session / cookie for the user. This means you won't likely need to check this access_token's validity for the life of the user's session. offline_access also creates new opportunities. You can store the access_token in your db as well.
Whenever you have a call that goes out to Facebook, check the exceptions, if you hit an authentication exception, clear the user's session and cookie. Next time it will force them to update their access_token, even if this process is invisible to the user.
I've done this on my apps, in most cases means I don't have to make queries to FB to see the validity of the access_token nor do I have to constantly get it on each page view. Our goal was to reduce latency on our apps, but Facebook was the biggest source of latency, doing this has cut it down considerably.
Answering my own question:
I used Javascript SDK for checking facebook authentication is available.
If fb authentication is OK and my application does not authenticated, i present user with a prefilled registration form of facebook.
If fb authentication isn't OK i present a facebook login button.
Registration Plugin authorizes my application and i call my fblogin.php to check this information using PHP SDK. When PHP SDK validates authorization, it stores this information on a session variable. So there's no need to check fb authentication on every request.
Login button does the same as Registration Plugin. These methods share same server-side functionality but their representation is different.
In order to catch facebook logout status, i used Javascript SDK to validate facebook authentication on every request. If user is logged out, my js code calls fblogout.php and current session is destroyed. There's a flaw on this method. If a user does not logout from my website explicitly, an attacker could do anything on behalf of user only disabling js on the same machine.
I cannot find a better solution with fast response time.
You can use one or the other or both.
You can use PHP SDK to generate the relevant URL's to send people to. And just wack that on a link.
Or you can use Javascript to make the Facebook Default login button.
After that you can use one or the other to maintain and verify the session.
I generally use PHP to do he grunt work with oAuth keys and use JavaScript SDK to make the nice Facebook buttons and some minor less important graph calls for session monitoring.
Anything that involves any heavy or multiple graph calls I push to PHP.
But there is flexibility there to do what you want. You don't have to use JavaScript SDK for login.
It's up to you if you want to verify every page load or not.
I tend to use the Javascript SDK to handle it and like Berk if the session is dead. Call a page redirect to a logout script.
As of the latest versions, PHP and JS SDK are now both able to access the same user session (login with JS or PHP [instead of having to do both]). Check out this blog post for a more detailed explanation and an example.
If you're worried about security, perhaps you could set the session cookie to expire sooner with session_set_cookie_params().
First, just remind you that you will need to save not only access_token, but ideally, you would like to save the user's facebook uid alongside with access token. This because typically, you will need to include the uid alongside with access token in your API call.
Second, from Facebook Documentation
Note: If the application has not requested offline_access permission,
the access token is time-bounded. Time-bounded access token also get
invalidated when the user logs out of Facebook. If the application has
obtained offline_access permission from the user, the access token
does not have an expiry. However it gets invalidated whenever the user
changes his/her password.
Third, the purpose of having access_token and uid, is to perform an API call, right? Start from there. Do the authentification, if only the access_token is (somehow) become invalid. How to check whether its valid or not then? Well, you can use cURL (Reference) or Proxy Library(but you may need to modify it lil bit, since it originally was written for CI) to make an API call as a validation proccess. Sample (*sigh, using my Proxy Library)...
// Suppose we are try to publish a status from our fb app
// $access_token hold the user access_token, which you saved into your database
// $uid hold the user facebook uid, which you saved into your database
$proxy = new Proxy;
// This is equal with perform regular HTTP POST request with cURL
$api_call = $proxy->http('post','https://graph.facebook.com/'.$uid.'/feed', array('access_token' => $access_token,'message' => 'foo'));
// Now we can validate...
// If the API success, it will be returned a post id, with json format
// if not, it will be outputing json like...
// "{"error":{"type":"OAuthException","message":"Invalid OAuth access token."}}"
// so...
$result = (array) json_decode($api_call);
if(array_key_exists('error', $result))
{
// Here you can perform an oAuth authentification, to get fresh access_token and update your database
// ...
// After it done, process the previous api call with valid access_token
$proxy->http('post','https://graph.facebook.com/'.$uid.'/feed', array('access_token' => $access_token,'message' => 'foo'));
}
The Facebook Connect documentation is rather limited. It doesn't really tell you what it is doing, only how to do it. I personally don't use either SDK. I have built my own framework for my development projects.
Both SDKs as well as the JavaScript in the tutorial are, IMO, fairly outdated.
If you want to stick to one of the FB SDKs here is my suggestion. Use the JS SDK only if your Graph API queries and the like are sent to a PHP backend via Ajax. Otherwise stick with the PHP SDK.
Introduction
Facebook uses oAuth v2. They describe two different methods of flow... Server side and client side. This would be implemented just the same as any other application authenticating against an oAuth v2 service. They both do the same thing. The only difference may be you can use 'code' as a request_type to get an authorization code for obtaining a token in the future.
Authentication
As far as FB Connect is concerned ll your script needs to to is make sure you have an auth token or auth code whenever you require authentication. If you don't have that then you need to get it. You can use the presence of an auth code or token as a condition for which FB button to show (login or logout).
Redirect the user to oAuth for authentication. Facebook has their oAuth implementation bundled in to their dialog API. More information on the oAuth Dialog here: http://developers.facebook.com/docs/reference/dialogs/oauth/
You can use the optional state parameter for something such as CSRF protection. It retains it's value after the process and is sent with the callback as a GET parameter.
Application Interaction
Basically you're going to write your application the same way you normally would. The differences would be:
Your user database no longer stores a password, just the FB UID. Also, according to the FB Dev ToS you really can't store any user information. If you want to store user information you need to get it from the user. You can populate this information for them with FB information, you just need them to submit it.
Your registration method won't have a form frontend posting to it any longer. It will be called when an authenticated user does not have an entry in the DB.
API Interaction
If you went with code instead of token you need to request a token by sending code. This is done with the Graph API oauth. This part is not documented at all other than in their authentication tutorial. http://developers.facebook.com/docs/authentication/
With your access token, whichever method you may have used to obtain it. You can now query the Graph API however you desire. This will return a JSON encoded object.
Conclusion
As far as a fast and secure implementation goes, the Facebook PHP SDK does the job. It handles everything I covered here, including the CSRF. How to go about learning it, I have yet to find decent documentation on it. Everything is either old or the writer doesn't really know and is going off of other tutorials.
Your best bet is to dig deep in those libraries and figure out how it works for yourself. Do some trial and error, experiment.
The way I learned was by writing my own framework for it. I suggest you do the same. You can extend the Facebook SDK classes if you like. It's really limited, but it gives you all you need. I took my most commonly used API calls and placed them in as well. I now have a very quick and simple end result that is driven from my library.
I think you don't need to implement SDKs.
1, You need to get permission from the user, to access his/her data. So you need to redirect them to Facebook. It is few (3-5) line of code in php.
https://graph.facebook.com/oauth/authorize?
client_id=YOUR_APP_ID&scope=email&redirect_uri=APP_URL
2, When the user arrive back to your site, come with $_GET['code']
http://YOUR_URL?code=A_CODE_GENERATED_BY_SERVER
3, You have to decode this code via Facebook get request, and get the access_token.
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE
3, After you have the access_token just run a /me?access_token GET request as often you need, to check the user is still there.
4, You can store the Facebook ID.
I think this is the fastest way. As far as I know the javascript sdk uses pop-up, what is blocked in most browsers.
This flow is detailed enough here: http://developers.facebook.com/docs/authentication/

Categories