Sharing session across multiple domains on same server in PHP - php

I need to implement a solution for one of my project, where I have multiple domains + multiple sub-domains and they all need to share the same session. All domains and sub-domains would be pointed to the single application which is connected to the single database.
Means if user logged in from any of the domain will be able to visit secure pages of other domains of the application. User may change domain via following a link or via opening a new tab in the browser.
I have gone through some articles and found some below mentioned solutions:-
Session in Database - What if other user from same network with same user agent hits?
iFrame message passing - I heard at somewhere, that iFrame renders on document load and, then checking session after showing some page content will annoy the user.
CURL request with CURLOPT_COOKIEFILE & CURLOPT_COOKIEJAR - I have played with this and it is working fine, but don't know if it is secure and not performance killer.
Single Sign On (SSO) - I need some R&D to implement this and it would be the last option.
Please suggest what to do?

Just to verify I am not wrong, you need to share user session across all your applications.
As rightly said above, you may use 4 of the options above. However, I would like to focus on first option which is putting session in DB and would like to suggest another option as keeping sessions in shared directory or server.
Sessions in DB - The answer to your question (What if other user from same network with same user agent hits?) is you will have different session id's value to uniquely identify each row in Table. So, no need to worry about it. But the disadvantage is, each time DB connection would be required and a query would be fired, when session is initialized i.e. for every single page.
Sessions in shared directory/server - Configure all your applications in a such a manner that all applications store session at shared location. Shared location can either be a directory or a secured server. This can easily achieved by using session_set_save_handler.

Related

How can I create a PHP session from one remote server to another?

I have ServiceSite.com (SS) and multiple GameSite.com's. All games authenticate through SS and then log in with their own personal databases. That's all done with a simple JSON API, no need to log into SS to get into a game.
I have the one goal of logging into a game and accessing the features of SS through the game, such as accessing a player's Contact List and Profile, both of which are shared between all games. While in GameSite.com/play, they'll hit a link to ServiceSite.com/contacts and get the response as if they were opening it from ServiceSite.com. I use JSON Web Tokens to manually log the user into SS, to simulate a real login to ServiceSite.com.
This works... so long as they're on the same domain. Meaning, as I'm developing a game, I'll use ServiceSite.com/tempgameurl and any call to ServiceSite.com has no problem establishing and keeping a session. But once the game gets its own domain, or if I'm working on my localhost, I cannot get it to recognize the session on subsequent requests. If I want a response, I will always have to pass the JWT token, which is not suitable for what I'm doing. The goal is to load a game, "poke" SS to create a log in, and then if a player were to visit ServiceSite.com, they would have the session as if they'd logged into ServiceSite.com's front page with their login manually.
In short, I expect that once I hit my first JWT request and make a session on ServiceSite.com from a GameSite.com, that's it, the session is made. But it seems to only actually make a session if I'm requesting from the same domain. I do see it create a session properly, filling in $_SESSION, but that data simply does not persist if the request originates from a non-ServiceSite.com URL.
Sessions and Cookies are domain dependent, it is a browser security issue. You cannot cheat this. However, there is a "trick" you can try, even though it is a bit more complex:
You need to set a cookie for each domain:
authenticate the user, emit a JWT code and create a key=>value type of record in a shared storage (database most likely). The key should be unique, the value should be JWT code and also set an expire time of 20-30 seconds.
in the response HTML you need to make the browser set cookies for the other domains. That can only be done on those domains. So you need to fool it with something like:
<img src="http://anotherDomain/setCookie.php?key=keyFromSharedStorage" style="display:none;" />
in the setCookie.php, check the shared storage and retrieve the JWT based on the $_GET['key']. Then set a cookie with that JWT.
You could pass the JWT directly, but passing a key that expires fast should be more secure. Add an image for every domain.
Instead of a cookie you can create a session on each domain. Same principle really.
Well try saving your needed data and sessions in database itself. It seems to be small amounts of data and logs.
After a game save the sessions on the database and open from whichever place you are at.

What happens if session name is same on two different websites?

I have a two diff. project on my XAMPP say it is Project1 and Project2.
When i login with Project1, i check authentication and if it is successful then stored session. The session name is $_SESSION['username'].
The above process is same with Project2.
now,to prevent direct access,i use this code(in both project):
if($_SESSION['username']=="")
{
header("location:index.php");
}
so when i login with Project1, i am also access Project2(without login).
To prevent this, i know that if i create diff. session name for both project then it is solved.
The above thing is in my local server. so i can create diff. session name for my all project.
But suppose my site is online and what happen if my session name is match with diff. site?
There is a millions of websites and there is a possibility that my session name is match with another website's session name.Then this might be happen that some user access my website with another website(in same browser) and he might be access my site without login.
So what happen if session is same for two diff. website? Can user is access my website without login?
If yes then what should i do to prevent it?
Thanks in advance.
UPDATE
according to #Let me see's answer there is a possibility that if two sites are running on the same server then they may share the data.
So suppose the server is sharing then what should i do to prevent it?
Sessions are (usually) stored using cookies, and cookies are domain-specific. So, it doesn't matter if google.com or evilhackerdomain.ru uses the same session name as your app; your cookies are only readable/usable by the domains you specify. Even in the unusual scenario that sessions are managed in some other way, it will be domain-specific.
So suppose the server is sharing then what should I do to prevent it?
To answer your follow up question. You can simply name your session on a specific website using session_name() before your session_start().
session_name('PROJECT1');
session_start();
this one-liner should do it.
Normally the sessionID of the sessions is stored in a cookie and it is related to the hostname and it can be shared by the multiple hostnames having the same domain. and as it is obvious that sessions are stored on the server . So there is a possibility that if two sites are running on the same server then they may share the data..Therefore you should always change the path for storing the sessions on the server for every different website
PHP Sessions are stored in Server. So there won't be any clash between same session names when you go live. Remember, You still have option to store your session in database, which helps you with more secutiry.
Nothing will happen. Because the other Site uses its own database (with own session and user tables). It would only matter if two Sites share the same Database, same tables and same session handling.
User cannot access without log in because of following reasons,
The session data is stored on the server. If two applications are running on the same server and the same domain name, then the possibility is there for them to share session data. Otherwise no conflicts with session values, if the domains are different.
I think if we use a security algorithm like MD5 to encrypt the session which you'll using to login. That will work without problem. For example:
$name_session='username';
$name_session=md5(md5(md5($name_session));
$_SESSION[$name_session]="username_logged";

check/ Getting a session name with php

I have two Domain site (Exmp: A & B) and two database,
function site A is for a payment method, so if a custumer buy a product, it will be direct for login first and
The site B is as a frontpage (web interface) only.
My question is : how can I get or check the session value FROM Site A and show the session_name in my interface website when the user is open my web at the same time.
Thanks in advance
You're facing 2 problems:
The session-id is probably stored on a cookie, and the browser will not send a cookie originated from domain A to domain B (unless you're talking about the same domain).
Even if you're able to have the session-id on both domains, for the data to be persistent across 2 sites, you're gonna need a shared session storage configured.
Possible solutions:
Pass the session-id over the URL as query-string parameter (not recommended for many reasons and has to be configured accordingly in your php.ini).
As for the storage: the common approach is to use a database as your session storage provider (hence making is 'shared').
Also, you may reconsider the use of session altogether, if you're only doing basic redirection maybe you can pass the data over a regular GET or POST request.

transfer session one website to another website

I have moodle LMS in three different countries (Ex:India, America, Eurppe). For these sites they have individual administrators. Suppose I am the main Administrator, I want to be able to manage all websites with one login.
If I login in Indian LMS and select America LMS in DROP DOWN, then the session should transfer to America LMS. Is there any solution for this?
If your sites are subdomains of the same domain you should consider reading this:
PHP Sessions across sub domains
To set cookie for the main domain and all subdomain. So you can read the same cookie from us.foo.com and also from eu.foo.com
Plus you should have a unique user database or more than one syncronized (i'd prefer the first option anyway).
You're going to encounter cookie domain restrictions as your first major barrier. Essentially, you can't read a login cookie (which are required for sessions to work) from a domain other than the domain that issued it, so a moodle instance at us-foo.com will never be able to read a login cookie from eu-bar.com.
The simplest way to route around this would be to use a separate login form. On submission, use JavaScript to open hidden iFrames to the login pages of all three sites, with the username and passwords passed via GET parameters. Moodle may not natively support login credentials being sent with GET; you may need to edit the login scripts.
There's a forum thread about doing just this with Moodle, though - you may be in luck.
But in any case, for a login multiplexing hack like this to work it will mean you have to keep the admin username and password constant between your three sites. You could enforce this in the database using triggers, if they're all run from the same database; otherwise you'll want to alter the password changing script to write those changes to the remote databases.
Is this a serious undertaking? Kind of. Unfortunately, it's not a very robust solution, and it is likely to be extraordinarily fragile when it comes to updates and the like. You may find that the best choice is to just login separately, particularly given that these hacks don't easily lend themselves to being embedded in the main login for the sites, and you'll need to use similar ad-hoc synchronization to make logging out take place across the network as well.

When to use URL/session/cookie variables?

I do a lot of php and javascript, but I think this is relatively language-agnostic question. Are there any best-practices for when to use each of:
URL variables
SESSION variables
cookies
I understand the inherent limitations of what some of them can't do, but it seems like their use can overlap sometimes, too, and those instances are what I'm really asking about.
EDIT
Just to clarify: I'm pretty familiar with the technicalities of which method is stored where, and which the client/server can access. What I am looking for is something a little higher-level, like "temporary user settings should live in cookies, data state info should live on the server, etc..."
Thanks!
In general:
Use URL (GET) parameters for sending simple request parameters to the server, eg. a search query or the page number in a product listing.
Use session variables, as the name indicates, to store temporary data associated with a specific user session, eg. a logged-in user's ID or a non-persistent shopping cart.
Avoid using cookies when possible. Use them sparingly to store settings that are tied to a particular computer / user profile, eg. a setting such as "remember my user ID on this computer".
Sessions are stored on the server, which means clients do not have access to the information you store about them. Session data, being stored on your server, does not need to be transmitted in full with each page; clients just need to send an ID and the data is loaded from the server.
On the other hand, Cookies are stored on the client. They can be made durable for a long time and would allow you to work more smoothly when you have a cluster of web servers. However unlike Sessions, data stored in Cookies is transmitted in full with each page request. You should use cookie if you need longer logged-in sessions.
URL variables (GET) are open and can be seen by user. They are also useful as it allows the user to bookmark the page and share the link.
PHP embeds the session id directly into URLs when cookies are disabled. Then, the session id becomes a value accessible thru an HTTP GET variable.

Categories