Using php sessions with ajax (mobile device) - ajax

I will explain my problem. I need to know if the steps below are correct:
The user enters their login details and these get submitted to the php server. If these are correct, I want to use the php code to start a session. However, because this is a mobile device I will be using html5 session storage. Now, my mobile website is all ajax based with no page reloads. So if the user submits the correct login credentials, I make an ajax response back to the user with what information? The SID/session_id of the session_start? Then, on the mobile device I place this session_id into the html5 session storage?
So, if these steps are correct, when the user then navigates around the website they are now logged in. And if they want to do something e.g. access a private page this creates an ajax request to the php server... this is where I am stuck. I assume that in this ajax request I send the session_id from the html5 session storage object, how does the php server use this id to prove the user is authentic? Presumably I need some kind of if statement and if it's not satisfied, send an ajax response back which my javascript will interpret as redirecting the user back to the login screen.
Many thanks if anyone can help me, it will be much appreciated as I am very stuck.
Note that cookies are not an option...

You could theoretically use HTML5 local storage to store the session ID, or transmit the session ID as a GET parameter in every request and pass it manually to PHP using session_id(), but I can't see the benefit. You might as well rely on cookies for this - they will be transmitted in Ajax requests.

Related

Cross/Multiple tab communication during login

In implementation of Login, I want to make sure if a user is already logged in one tab of the browser and opens the same web site in another tab, he gets redirected to homepage rather than the log in page. It's an ideal scenario as it happens in all the web site. I am achieving the same by storing logged in unique user token in local storage. Is it the best way to achieve it? Kindly guide! is it safe? If not how to go about it?
Just consider everything on the client as tainted or possibly manipulated.
So basically you should always check on the server side if the client has a valid session and only then deliver the homepage to it.
I would use a cookie set by the server side - just a random id bound to the actual client session on the server.
So the client could mess with that, but would have a hard time to guess another (also random) session id.
The cookie should be cleared by the server if the user logs out.
Then I would check on every call if he has a valid session id and if not directly send him to the login page by a redirect. Additionally you could then send him from the login page to the homepage whenever he is already logged in.

How to persist session data in an AngularJS application?

I have this web app written in AngularJs that uses cookies to authenticate the requests in a REST API.
Once the user logs in, the cookie is received and saved in the browser and all subsequent requests send the cookie along to the server. There is a 'User' service/object that saves the isLoggedIn and username values (for UI display/flow). Now, if I refresh the 'index' page, the app restarts. This means that my 'User' object will be cleared. I can check the existence of the cookie and, if it exists, I can re-set the User.isLoggeIn as true and go from there, but I still need to get the username, id, etc. So, my question is: should I create some sort of 'ping' endpoint in the API to verify if a cookie is valid? And if so, the API would send me back the user id and username... OR should I persist the user data in LocalStorage (or some similar cross-browser thing) and just assume the user is logged if the cookie exists? Any other subsequent requests to pages that need authentication would be automatically verified. So, this question really only applies to the scenario where the user refreshes the index page - hence, restarting the web app. I want to know the user data because I want to show a 'user homepage' instead of the 'public homepage'.
What do you think?
You should depend on the server for this. Creating something like GetCurrentUser method on the server. If the user is logged on this returns all the properties of the user.
You should even use this server api to get the user data after authentication completes. So the authentication become two step process first the user is authenticated, on success another call is made to server to get current users details.
Using client side local storage for this would not be ideal because you need to do lot of book keeping, in terms of cleaning the logged in user on log out or session expiration.
Also cookies from server would have expiration times an all, and making decision just based on cookie existing on local storage may not be optimal approach.

What's the best way to use HTTP Authentication in an Ajax Application that's not 100% AJAX

I have a standard HTML login page, which I would much rather use than the standard HTTP authentication pop-up provided by browsers. Today, I am using session cookies to keep track of the session after logging in, but I'd like to be stateless and pass the HTTP authentication every time. The web services I am hitting already support this, so this is a browser-only issue.
Adding authentication credentials is trivial in jQuery, but I don't know how to keep them around. If you go from the login page (a jsp) to the Home page (another jsp) you clearly don't keep the username and password fields from the login page. I know some browsers will store your HTTP authentication credentials if you enter them from the pop-up, but I don't know if they get stored when using an XHRRequest. If they do, is there much consistency among browsers?
Also, the user needs to be able to "sign out" of the application, too. If the browser stores the authentication credentials, is there a way to clear them using JavaScript.
I feel like I can't be the first person to try to solve this. Is there some jQuery plugin or something that already handles this? Or is it simply not possible to do what I'm trying to do?
You have 2 options:
1) Client-side storage of credentials -- not a good idea. For obvious reasons you don't want to store the username/password on the client. If you had a hashed version of the password, it might not be so bad, but still not recommended. In any case, if you're going to store on the client side, you either have to use a cookie, or HTML5 local storage (which is not widely supported, yet)
2) Server-side storage of credentials -- typically done with sessions. Then the resultant Session ID can be passed back to the client and persisted in either a cookie or in the URL of each subsequent AJAX call (?SESSID=xyz for example)
The server-side approach would be the most secure, reliable, and easiest to implement
Okay, I'll take a stab at helping ...
Firstly, understand how HTTP authentication works. There are two versions - Basic and Digest. Basic transmits in plaintext, digest is encrypted. With these types of authentication, the username/password are passed in the HTTP header with every single request. The browser captures these at login and they are stored in an inaccessible browser session cookie which is deleted when the browser session is closed. So, in answer to one of your questions, you can't access these from javascript.
You could create your own session cookie variables for username and password. The jQuery functions for this are really simple. See jquery-cookie module as one example of how to set session cookies. These could be retrieved from the session cookie and sent with each ajax request and validated in the server. However, this is not a particulary good way to do authentication since sniffing the network will allow anybody to easily grab your auth details. But, it would work.
Using session cookie based authentication where the session ID is sent sent with each request is the best way to do this. At the server side, you need to have a function called for every HTTP request. This function should do the following:
check to see if the session has been authenticated
if no:
redirect to login screen
if yes:
do authorization and allow the user access to the page
Most web frameworks support session cookie authentication and the management of session ids at the server. This is definately the way to go.
This is interesting one.
Manage user sessions on server by use of cookies. Create a session when user first accesses the login page and pass the session id/key as value to one of the cookie via response. When the user is authenticated put user "key" info in cookie and "values" in application context at server. Once user is logged, any subsequent request will be authenticated based on session cookie value at server. Authorization will be done based on user "key" passed as cookie value.
On logout clear the session based cookies from server and refresh the site to default page.
Cookies are bizarre with different browsers - just a note ;)
Hope this helps.
Update
The answer below was posted in 2012 and the links are mostly dead. However, since then, a more elegant standards-based approach to the same solution appeared using JSON Web Tokens. Here is a good blog post explaining how to use them.
Most answers miss the point, which is to avoid having any server-side session. I don't want any application state in the server. I'll award the bounty to answer that came closest, but the real credit goes to the rest-discuss group and Jon Moore for the correct answer and to Mike Amundsen for helping me to actually understand it.
The best answer I've gotten is to use a cookie, but not the typical automatic session id cookie given to you by most application servers. The cookie (which will automatically be sent with each subsequent request) is a user identifier and time signed by the server. You can include an expiration time with the cookie so it simulates the typical 30 minute session on a server (which means you have to push it forward with subsequent requests) as well as keeps the same cookie from being valid forever.
The XHR/AJAX part is a red herring. This will work whether you are doing XHR requests or an old-fashioned page-by-page web application. The main points are:
The cookie is automatically sent on subsequent requests so there's no
special scripting required - it's just how browsers work already.
The server does not need to store any session for the user, so the user
can hit any server in a cluster and not have to re-authenticate.
Slightly interesting in that you consider pushing some of the authent to the client. If you want a conventional solution, KOGI's server-side suggestion is the way to go.
But you also seem to be asking questions about memory leaks involving your user supplied secrets. Good questions. But to take a general stab at answering that I'd say it would have to be browser specific. It's browser internals, javascript engine internals -dependent where a client side application (i.e., the browser, or js in the browser) is storing the values the user inputs.
Most likely those values are not replicated needlessly throughout memory, but there's no way to guarantee that. Apart from responsible javascript coding practices, there's nothing you can do to guarantee the limit of locations of user inputs.
Slight digression
The basic point is if you store it on the client it is not really secure -- unless, the serve stores encrypted information on the client with a key that only the server (or the user via their correct credentials), has. So you could conceivably code a JS application to do some authent on the client -- much the same as how bank card (used to?) do POS authent by checking the PIN to the PIN on the card, and not back at the DB. It's based on the (somewhat flimsy) assumption the user has no direct read/write access of the "dark area" cookie/local storage on client / mag strip on bank card. So I would only advise this as disqualifier for false authents and not as a sole qualifier for the credentials.
Main point
If you do want to be stateless, just store user credentials in localstorage, or as a cookie but encrypt them with a server key. When you need them send an XHR with the encrypted / use stored credentials to the server over HTTPS, let your server decrypt them and send them to the callback. Then pass those cleartext of HTTPS to do your authent.

Ajax Request for same domain only. Restrict Cross domain ajax

I am new for jquery with limited knowledge.
I am doing ajax request to fetch much imp information to display into the page without reloading the page.
It is done.
But i am worried about. Any can do the call from other server to that php file to get information details.
My Question is that How i can restrict the others to access that file using ajax or directly putting the file path in browser address bar?
Please Help in it.
Thanks in advance.
An ajax request is like any other http request.So you can add the security layer on your server using session-cookies, which will work only if user is logged-in(or you can create dummy sessions for pages that don't expect user to be logged in)
You'll need to include a CSRF token in all your AJAX calls. This prevents CSRF attacks since the attacker cannot put the right token in its submissions.

Securing an ajax request

i have a website that uses session cookies for security. it works fine and all, but any ajax requests right now are not secure. example being lets say a user is on a page. they can only get to this page if they are logged in with a session - so far so good. but now the ajax request they ask for is
ajaxpages/somepage.php?somevar=something&anothervar=something
if any other user decides to just go to that link themselves (without a session) they still get the same ajax output that was meant for logged in people.
so obviously im going to have to pass session data across when i send an ajax request. anyone have any tips for the best way of doing this? ive never done this before and would rather use trusted methods than make up my own.
The ajax requests work just like any other request to your website and should return the same session cookies as the non-ajax request. This is pointed out in this question. If you aren't getting the session cookie, perhaps something else is wrong.
Having an ajax output isn't necessarily a vulnerability. It entirely depends on what data is being transmitted. I am not sure what platform you are using, but most web application development platforms have a session variable that can maintain state between requests.
What you should have in place is way of marking the user as being logged in from the server side. I php this would look like:
if(login($user,$password)){
$_SESSION['logged_in']=true;
}
Then you can check in a header file if they are allowed to access the page:
if(!$_SESSION['logged_in']){
header("location: http://127.0.0.1/");
die();
}
(If a variable isn't set it is also false.)
There are a few things you need to keep in mind. This is a vulnerability:
if(!$_COOKIE['logged_in']){
header("location: http://127.0.0.1/");
die();
}
The user can control $_COOKIE, so they can tell you that they are logged in.
Another vulnerability:
if(!$_COOKIE['logged_in']){
header("location: http://127.0.0.1/");
}
header() doesn't kill the script. In fact it still runs, so it will still output but it won't be displayed in a browser, you can still use netcat/telnet/wireshark to see the data.
Use the same security check on the pages that handle the ajax request.
Since that is a PHP page, I don't see why you couldn't perform authentication on the PHP side. If authentication is successful, send back the data. Otherwise, send back an error message. AJAX aren't that different from any other request.
Just let ajax carry the session cookie, there is no problem with that, but you must check if the user is logged or not at the end, and you might want to add some CSRF token for your request, just in case ...
And try to validate the referrer, so you can check if the request was sent from your website, and your website only, it's not a good practice to let user open your request url for ajax in their browser ....
And if you have query in your script, to get some data from your database or else ... don't forget to sanitize the input, and escaping the output, based on what kind of data that you need, once more just in case ...

Resources