My application has a PHP server and a client (a JS single-page app). They are separate projects and deployed in different domains. The client consumes a RESTful API exposed by the server.
This application is to be integrated with a third party which handles authentication, so users cannot login directly. Our server just receives an SSO token (which comes appropriately signed so that we verify its integrity).
We also enforce security at the transport layer for all requests.
What I'd like to do is, once the SSO token is verified, start a session of my own and then redirect the user to the client. I thought that once the session was created the browser would automatically send the right Cookie header in the asynchronous API calls, but it doesn't seem to be the case.
Is this deliberately disabled due to security reasons?
You must set withCredentials to true for cross-origin XHR requests to include cookies.
The CORS response must also say Access-Control-Allow-Credentials: true (which is why widthCredentials defaults to false).
I thought that once the session was created the browser would automatically send the right Cookie header in the asynchronous API calls
Not for cross-domain requests for CORS-enabled ressources (which seems to be the case here, if I understand your described setup correctly.)
To make that happen, you need to set the withCredentials flag.
I'm a PHP programmer by profession. So, I don't have any idea about iOS and Android coding.
The scenario is there is one website developed using a Social Networking PHP software titled "PHPFox".
Now there are two similar mobile apps which exactly replicates the functionality of this website. One mobile app is in iOS and another is in Android.
So, I've written a set of RESTful APIs where I'm accepting the request from mobile app, parse the request, pass the request parameters to the function which does the same job for website, get the response from this function, convert it into JSON format and sent it back to mobile app. For iOS and Android app I'm using the same set of REST API files.
When user logs in, the REST API for login gets called. Eventually the PHPFox function for authentication gets called, a security token is generated along with some other user data. With every login the different security token is generated by PHPFox. This data is set into the session. Now every time I call any of the functions through any REST API file the security token generated at the time of login is verified and only upon successful verification of token the PHPFox function gets called. This verification process is done internally by PHPFox. So no need to pass the security token explicitly or implicitly to any REST API call.
Till now everything works absolutely fine.
My doubt starts from here. I don't know whether the session is maintained in iOS/Android app. So, if session on server i.e. PHPFox gets timed out then what will happen to the app? Will it crash? Will the user have to login again? If user kills the app on the device and again comes to the app, does he/she have to do the login process again?
There are too many doubts in my mind. I get totally confused with these things.
Can someone please put more focus on the issue I'm facing? It would be really great if you could explain in detail.
Thanks.
REST is sessionless for its nature. You need to generate a token when user logged in. You must save this token on your mobile client.
For every request, you need to attach a valid token in request header and check it at server side.
If token expires, the token stored on a client is not valid. So, you need to login again because of 401 response. If token it's not correct you need to responde 400.
I hope that I'm helpful for you.
Unlike web browsers, iOS and android apps cannot maintain sessions. Usually, once a user has logged in (login credentials verified from server), its login credentials are saved on client side. Then the app gets data from server using session less REST api calls. This is how mostly it is done in mobile applications.
However, if you want the server session and mobile app go hand in hand (which i don't think is a good idea), the way is
1) When the user logs in, a security token is generated on the server side and saved on both server and client side.
2) The mobile app will be able to communicate with the server as long as the security token is valid.
3) When the session expires, the security token becomes invalid. Now there must be an understanding between server and client about the response when the session is expired. Now the mobile app must redirect the user to login page again. The user will login again and then communicate with the server. This should happen every time the session is expired.
If your are using Oauth 2 for athentication, here is the common setup:
User logs in on mobile app
If the credentials are ok, the server returns the access token, a refresh token and the token's lifetime
The mobile app stores those values + current timestamp
On the server's side, a garbage collector is configured to clear expired tokens
Before making any api call, the mobile app checks if the token is about to expire (with the help of the stored values). If the token is about to expire, the app sends the refresh token which instructs the server to generate a new access token
If you want users to stay connected, the app can be configured to check the access token periodically and request a new one if it's stale
Hope this helps.
Cheers
Your server should be completely stateless, and so no session should be stored.. a REST API is effectively just a data abstraction layer with optional security (through token)
So you API expose an authentication service, which will respond with an Authorization token to be used on subsequent requests as a header, this token should be a 1to1 relation with each user, and Universally Unique. It should also have an expire time, at which point your server responds with appropriate error response requesting your app to refresh the token, which can be done either via a separate refresh token system, or requesting that the user logs in again to refresh the token.
It is the APP which should maintain the state, not the server. The server is merely there for data purposes, and so should not rely on any kind of session based authentication.
A session is "something" that lives on the server. It can be an object storing details about the user (for instance session id, username, email address...) or any other data that will be required to process future requests (such as shopping cart details, delivery address...).
That "something" is typically an object, which can be stored in memory, in a database or even serialized and saved to the file system (I believe this is the default in PHP).
So when you say "I don't know whether the session is maintained in iOS/Android app", I'm afraid that doesn't make sense. Only the server can maintain sessions.
Typically, the only thing that the client would know (web browser or mobile app) is the session id (in the form of a token or GUID). That is the only thing the client/app needs to remember and it needs to be sent alongside any request to the server.
It could be stored as a cookie and/or sent to the server as a request header.
Then the server will read the session id/token from the cookies or header and will retrieve the session details from the place where it stores sessions (file system, memory or database). That is what happens behind the scene when you call session_start().
To read more about session handling and how to create custom session handler (which might be required in your case to get a token from the request headers):
http://php.net/manual/en/function.session-start.php
You should not worry about the session from the mobile development side.in Android we use SharedPrefrence and NSUserDefaults (Flag which maintains the session locally).
I dont have any experience working with PHPFox but this is how a mobile frontend should ideally handle the issues:
Case 1: Mobile app actively talking to server:
Session timeout stamp keeps bumping up and session stays alive.
Case 2: Mobile app active without any server communication (e.g. incoming phone call, moving between apps etc.):
Server session may or may not timeout.
If it times out, next query to server will fail auth and return an error.
App consumes this error and gracefully redirects to login screen with a message toast urging the user to login.
(This happens in my banking app)
Case 3: User kills the app on device and relaunches it:
The app should store the token either in sqllite or shared preferences. (Always logged in apps take this approach)
Upon relaunch, app can query the server with the presistent token.
If session is alive, communication goes through and user can
continue. If not, user goes to login screen as in Case 2.
I'm making an online user account system for a game being created in Unity3d. The Unity application sends WWW requests to php files, and as a result some action is performed and the application gets feedback.
However, I've noticed that this method allows any application to send these requests. Can this be avoided? Is my method of communication between the client and the server flawed?
How can I make it so that only my application can send these requests?
Look up session key (or sesskey).
Basically it's a random string generated on the server and is valid as long as the session is active. This session key is sent to the client side and is one of the values in any server call. Each time the server compares the string to the one it has.
whenever the user logs out the session key is destroyed and a call from any third party application using the last sesskey will be denied.
Now I have a web server written with php. And there some php script files for database accessing. I'm writing a Qt app to send get/post request to the remote php scripts. However, it's not convenient to verify user identity for each request. So, I want to use session control on the web server. But I don't know how to do in Qt application.
As Orangepill and PLB said, the solution is Passing cookies to the request url, you may refer to QNetworkAccessManager::setCookieJar.
Steps
Instantiate the QNetworkAccessManager object and call setCookieJar for it.
Send POST request to the authenticate page which activates a session. Then you will have cookies got from the page in the cookieJar.
Send requests to the pages under the domain will with the session alive.
What is the best way to write an android application that logs into a server? I am thinking I do not want to maintain a socket, so I think I want to avoid that, I think I want to use the http protocol. My question with that is, on the server side, ideally I would like to use PHP to handle the GET/POST calls from the android app, but I don't know how to return (using PHP) information that my app can handle and not just an html file.
So for example, the facebook app for android. When you first download the app, you login and then the app maintains your connection, but obviously the app is not another web browser, but a regular app that presents its information as if it were a web site. How does the app pass the session cookie so that the PHP $_SESSION variables maintain themselves? How does the android app handle the data that comes back?
If I send a get requestion to htt://www.test.php can the PHP code that executes on the server return a custom set of data? Will the $_SESSION variables be automatically maintainted?
Thank you
You can send a get/post request to log on the server. The PHP page can return JSON or XML. Then your Java (Android) code will have to parse that response.
You can have the PHP page log first, and then start a session. Maybe generate a token key and store this in the database, and then return this to the android app. Android app will get this token (after parsing), and probably save it in a preferences file. This approach is basically a custom session. You will have to figure out things like expiration of token, etc.
There might be a way to store PHP sessions, but not sure how an app behaves differently from a browser. I think sessions can be little bit more complicated with apps.
More discussion here: php session destroyed in android application
You just need to create Server Side API which receives and sends data back to Client. Server start session, when API is requested, and Client receives PHPSESSID which is used to keep session opened. On Client, you use cookie for sessions.
Read about sessions: PHP Sessions (simple) and Session Handling (comprehensive)