session id is changing after every request - php

I have a php backend for API's and I am using Angular5 for my frontend. I was wondering, how can I handle sessions on Angular? I tried reading the documentation and was unable to come up with anything.
After login if I am making any request it is creating different session id?

for the frontend, if you want to access the values from the browser and send it to sever as well try storing the values in local storage which are very simple to set as well as to get in angular.
just you need to write is
localStorage.setItem('yourstoragename', JSON.stringify({ token: token, name: name }));
to access this you can write as
var name = JSON.parse(localStorage.getItem('yourstoragename'));
console.log(name);

Session data is something handled by the server-side, and the client (Angular in your case) is not able to read it.
The client (Browser for example) can get the session_id, and store additional information to be kept (Not secured information, as you can see all cookies's data with DevTools for example).
In most cases, after post of the login, the server will give you a token that you can use with later requests, so on your side you have to keep that token, and use it with the following requests to the PHP Server.
Refs:
https://coderwall.com/p/8wrxfw/goodbye-php-sessions-hello-json-web-tokens

I was able to use $_SESSION in my PHP to handle user login with ionic-angular-3.9.2. Using {withCredentials: true} in the Angular HttpClient requests was the part I had a hard time finding. I posted a detailed answer in my reply to this question (other solutions are there also):Why session PHP can’t be used with Ionic?

Related

How to secure PHP API from unauthorized AJAX calls (Phonegap mobile app)? [duplicate]

I want to use post to update a database and don't want people doing it manually, i.e., it should only be possible through AJAX in a client. Is there some well known cryptographic trick to use in this scenario?
Say I'm issuing a GET request to insert a new user into my database at site.com/adduser/<userid>. Someone could overpopulate my database by issuing fake requests.
There is no way to avoid forged requests in this case, as the client browser already has everything necessary to make the request; it is only a matter of some debugging for a malicious user to figure out how to make arbitrary requests to your backend, and probably even using your own code to make it easier. You don't need "cryptographic tricks", you need only obfuscation, and that will only make forging a bit inconvenient, but still not impossible.
It can be achieved.
Whenever you render a page which is supposed to make such request. Generate a random token and store it in session (for authenticated user) or database (in case this request is publicly allowed).
and instead of calling site.com/adduser/<userid> call site.com/adduser/<userid>/<token>
whenever you receive such request if the token is valid or not (from session or database)
In case token is correct, process the request and remove used token from session / db
In case token is incorrect, reject the request.
I don't really need to restrict access to the server (although that would be great), I'm looking for a cryptographic trick that would allow the server to know when things are coming from the app and not forged by the user using a sniffed token.
You cannot do this. It's almost one of the fundamental problems with client/server applications. Here's why it doesn't work: Say you had a way for your client app to authenticate itself to the server - whether it's a secret password or some other method. The information that the app needs is necessarily accessible to the app (the password is hidden in there somewhere, or whatever). But because it runs on the user's computer, that means they also have access to this information: All they need is to look at the source, or the binary, or the network traffic between your app and the server, and eventually they will figure out the mechanism by which your app authenticates, and replicate it. Maybe they'll even copy it. Maybe they'll write a clever hack to make your app do the heavy lifting (You can always just send fake user input to the app). But no matter how, they've got all the information required, and there is no way to stop them from having it that wouldn't also stop your app from having it.
Prevent Direct Access To File Called By ajax Function seems to address the question.
You can (among other solutions, I'm sure)...
use session management (log in to create a session);
send a unique key to the client which needs to be returned before it expires (can't
be re-used, and can't be stored for use later on);
and/or set headers as in the linked answer.
But anything can be spoofed if people try hard enough. The only completely secure system is one which no-one can access at all.
This is the same problem as CSRF - and the solution is the same: use a token in the AJAX request which you've perviously stored eslewhere (or can regenerate, e.g. by encrypting the parameters using the sessin id as a key). Chriss Shiflett has some sensible notes on this, and there's an OWASP project for detecting CSRF with PHP
This is some authorization issue: only authorized requests should result in the creation of a new user. So when receiving such a request, your sever needs to check whether it’s from a client that is authorized to create new users.
Now the main issue is how to decide what request is authorized. In most cases, this is done via user roles and/or some ticketing system. With user roles, you’ll have additional problems to solve like user identification and user authentication. But if that is already solved, you can easily map the users onto roles like Alice is an admin and Bob is a regular user and only admins are authorized to create new users.
It works like any other web page: login authentication, check the referrer.
The solution is adding the bold line to ajax requests. Also you should look to basic authentication, this will not be the only protector. You can catch the incomes with these code from your ajax page
Ajax Call
function callit()
{
if(window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function(){if(xmlhttp.readyState==4&&xmlhttp.status==200){document.getElementById('alp').innerHTML=xmlhttp.responseText;}}
xmlhttp.open("get", "call.asp", true);
**xmlhttp.setRequestHeader("X-Requested-With","XMLHttpRequest");**
xmlhttp.send();
}
PHP/ASP Requested Page Answer
ASP
If Request.ServerVariables("HTTP_X-Requested-With") = "XMLHttpRequest" Then
'Do stuff
Else
'Kill it
End If
PHP
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
{
//Do stuff
} else {
//Kill it
}

Comunicate NodeJs with PHP and viceversa

I put in situation:
I have a website entire make in PHP 5.3 and MYSQL, the site need to user to login for get access, the login "simply" check user/password and create a $_SESSION in the domain with the user ID and other user non-personal data.
In PHP i need to read this $_SESSION to detect if user is logued.
Now, i think in create a NodeJS real-time chat with websockets (only work in last browsers obiously, but i looking for pure HTML5 site, not external client-js like socketio.js), but here is my problems:
First problem I need to get the $_SESSION['user'] in the NodeJS, for make this i need to "pull" from PHP TO NodeJS, send a message like "update-this-user-auth" with the $_SESSION['user'] data, but the problem is, first HOW is the best way to pull from PHP Server to NodeJS Server runing in the same (or not..) machine.
And second problem HOW identify the user in NodeJS, because the user have $_SESSSIOn in PHP but i dont know if the request is from user nº1, nº32 or nº 999999.
For the problem of the comunicate from PHP to NodeJS I read some posts, and get 2 ways:
CURL User, usin PHP Curl to "call" a NodeJS service, and send-read data from PHP to NodeJS
Sending messages from PHP to Node.js
DNODE, i found this googling, have good look, but require some extra librarys, and i like to make the code clear and preferably simple.
http://bergie.iki.fi/blog/dnode-make_php_and_node-js_talk_to_each_other/
I thanks to all ideas and comments for the best solution to this two problem.
With PHP:
You can save a random generated key in the database, associated with user's ip, user id and any other session information (time created, last active, expiration date...). Also, save that key in a cookie too.
With Node.js:
Read the cookie, find the key in the DB and check if the session is valid or not.
So, basically, instead of storing all info in PHP, use a shared storage like for example a DB.

consuming two consequence Rest web serivce using PHP, curl or file_get_contents?

I need to first use webservice to login and then set the cookie in browser, then call another webservice and get some user specific data.
When I paste rest webservice on browser (first logging, then another one to get user specific data) it works fine.
But if I call those two web services using php (used twice) with
file_get_contents("url to login");
$Userdata=file_get_contents("url to get user specific data");
it seems $Userdata has no data, as if previous line file_get_contents("url to login");
has not been executed.
Any idea how to do this?
You can send cookie with get_file_contents via stream context (see PHP - Send cookie with file_get_contents) but if you want to use the cookie to log in, you have to somehow grab the cookie set by first request. It could be easier to use cURL. There is other question with accepted answer to describe this with cURL: file_get_contents receive cookies

Any idea how to do (1) php authentication (2) launch a flex app which knows the user has already been authenticated

Almost everything is in the title :
Here's what I'd like to do :
A nice html page with a php authentication process (http first then https & so on)
Launch a flex app which knows (I don't know how (this is the actual question !)) the user has already been authenticated and display his/her stuff he/she has to do for the day (or whatever...).
Of course if someone try to call directly the flex app I would display an "authentication error" message and then redirect to the authentication page.
I'm sorry for my English which is perfectible.
I was thinking about the session cookie : first authenticate then ass a variable on the server side, something like :
$_SESSION['authenticate']=true
Then, on the flex side, just send the cookie and ask if the user is properly authenticated, something like calling a php web page like :
https://is_authenticated.php?php_session=xxxx
Thank you
Olivier
What are you using on the server side? Remember that you shouldn't do anything in the flex application other then send the SESSION ID along with any requests. Any time where the client checks security, you have a bug. The server must validate the session and determine if the request is allowed.
It sounded in your last comment that you are worried about people manually calling a web page. Each page must check to see if the user is authenticated. I don't know your specific application, but you may try looking at AMFPHP and see how they do session authentication. Good luck!
Your on the right track!
You could use session-authentication, these links might help you out:
http://www.zend.com/zend/spotlight/sessionauth7may.php
http://www.tizag.com/phpT/phpsessions.php
There is also the possibility to use http-authentication
http://se2.php.net/features.http-auth
however http-authentication is not as flexible as session-authentication, and also means some more configuration on the serverside.I would therefore recommend you to stick with sessions.
This is exactly what I would do.. A few things to consider from a security standpoint:
If your php service (from flex) gets an unknown session token, always generate a new one. This also applies to your PHP application and is often overlooked.
I would generate the swf with javascript, and manually insert the session cookie using javascript. This way people won't download and safe (or cache) your php pages with sessions that are invalid in the future.
Even better would be to use a separate token other than the session, and on the server figure out what the session id was based on this flex token.

How can I get Flash to share the browser cookies/session?

I'm building a PHP-based web app and am integrating a Flash-based charting engine. The Flash chart needs to make a AJAX request for its data. This request fails because it is seen as a new user agent and doesn't contain the PHP session cookie to identify it. So, it gets redirected to the login page.
I've read a few hacks to make this work, including supplying the session ID on the querystring, but that opens up security holes. How can I get Flash and PHP to share cookie-based session state automatically and stay secure?
In IE it will work naively. In firefox, the only way to achieve this is to POST the session id into the flash script (the php processor that is), and have it restore the session from that.
If the session cookie is initiated early enough, then it should be OK. I've had a similar problem with cookies shared between JavaScript AJAX and Flash requests (if you want to call that AJAX too, go ahead :-) ), and we solved them by making sure the JavaSCript finished the request that initiated the cookie early enough so that when the Flash sent the request, the browser already had the session cookie.
Also making sure the cookie path was set to "/" was a good idea.
That being said, if you can't get it to work - as dirkgently said - you can store the information in the HTML DOM using a JavaScript AJAX call, and then fetch it from the Flash object using an ExternalInterface call. But do make sure to set at least "allowScriptAccess=sameDomain" on your Flash object
You should be aware that transmitting a session ID in a Cookie: header, or in the argument field of the GET HTTP directive is of no different security.
Use ExternalInterface to talk to the Flex chart. Some browser related information can be passed around via the LoaderContext and BrowserManager classes as well. Dig in a bit into the AS3 documentation.
you can try and send to php 2 parameters one session_id and a second one that is an key that combines some information from the client ( ex ip ) and encrypt it with a key stored on the server and on the request from flash you check to see the second paramaters matches the client request, this way if somebody trys to do a session stealing they cant because they will not match the second param

Categories