Sessions of different systems on the same server

Asked

Viewed 821 times

2

Scenario (example)

I have 2 systems:

  • Sistema Padaria
  • Posto System

Details

  • The database is separated, then each system with its users and passwords.
  • There’s "common user" among the 2 (e.g.: joão.silva)

Problems

If I don’t wear one session_name() different for each system, if I am logged in with the "Joao.silva" in the bakery system, and enters the station system, it will enter directly, as if it had authenticated.


Doubts

  • When to use the session_name()?
  • When to use the session_id()?
  • What else seguro?
  • Something more important in this context?

PS.: I appreciate good links for study. Please avoid searching on Google without at least checking if the content is complete and currently used.

2 answers

4


First let me explain the main, the sessions are global, if they are on the same server and domain then they can be accessed by different applications.

However it is possible to limit the folders that can access the session cookie by adjusting the session_set_cookie_params, something like:

 setcookie(time() + 3600, '/sistema_a/'); //Somente acessivel na pasta sistema_a
 session_start();

But of course this control is only in the cookie, it is still possible to get the values by changing if you use the same session_id.

Some details:

  • session_name will only pick up the call session at the moment
  • you can’t read two sessions at once, you can even do some maneuvers in the code but will not work as well or in such a practical way.
  • session_regenerate_id does not guarantee a general security, but one place that really can be useful is against sequestration of sessions, which has nothing to do with your problem

How the session works?

When using session_start will be created a cookie will have you a random code that will refer to a file in the folder /tmp (or c:\caminho\para\o\php\temp or c:\window\temp in the case of Windows Server), that is, the data is in the back end, there is no way anyone can steal them unless you as a developer have done something very wrong, an explanation about data exposure in the back end:


But going back to your applications, if you are the creator of both or at least understand the structure of both of the sessions, what you can do is check if you are already logged in and try to import the data by passing them to the format of the desired, for example:

  • System A, is with session_name called SYSTEM_A and the format of the session:

    array(
       'sys_a' => array(
             'idUser' => '<id do usuario>',
             'name' => '<nome do usuario>',
             'update' => <ultima requisição HTTP atualiza esta chave>
       )
    )
    
  • System B, is with session_name called SISTEM_B and the format of the session:

    array(
       'sys_b' => array(
             'id' => '<id do usuario>',
             'user' => '<nome do usuario>',
             'lastactive' => <ultima requisição HTTP atualiza esta chave>
       )
    )
    

They’re similar, but they’re not the same, so assuming you’re logged in to system A and will open the system B, you could create a file and include on top of all called sync_from_sis_a.php, thus:

<?php

require_once 'sync_from_sis_a.php';

The content of sync_from_sis_a.php would be:

<?php
session_name('SYSTEM_A');
session_start();

//Verifica se NÃO esta logado no B e se ESTA logado no A
if (empty($_SESSION['sys_b']['id']) && isset($_SESSION['sys_a']['idUser'])) {
   $id = $_SESSION['sys_a']['idUser'];
   $nome = $_SESSION['sys_a']['name'];

   session_write_close(); //Finaliza o handle

   session_name('SYSTEM_B'); //Agora no sistema B
   session_start();

   //Copia os dados da sessão anterior para a sessão do sistema B
   $_SESSION['sys_b']['id'] = $id;
   $_SESSION['sys_b']['user'] = $nome;
   $_SESSION['sys_b']['lastactive'] = time();
}

If you are not logged in to system A then it will open system B normally asking for login.

The same should be done in system A, check if you are already logged in, so if you do not have to check if you are logged in to B, then create a file called sync_from_sis_b.php and include at the top of all system A, the file should be like this:

<?php
session_name('SYSTEM_B');
session_start();

//Verifica se NÃO esta logado no A e se ESTA logado no B
if (empty($_SESSION['sys_a']['idUser']) && isset($_SESSION['sys_b']['id'])) {
   $id = $_SESSION['sys_b']['id'];
   $nome = $_SESSION['sys_b']['user'];

   session_write_close(); //Finaliza o handle

   session_name('SYSTEM_A'); //Agora no sistema A
   session_start();

   //Copia os dados da sessão anterior para a sessão do sistema B
   $_SESSION['sys_a']['idUser'] = $id;
   $_SESSION['sys_a']['name'] = $nome;
   $_SESSION['sys_b']['update'] = time();
}

Note: all this explained above is hypothetical, there is no way to know the functioning of your systems, it may be that use encrypted session or that has a complex structure, there is no magic way to synchronize 2 different systems, even more if it was not you who did, the only solution is for you to understand both systems or for them to provide Apis to facilitate this type of operation.


Answering the questions

When to use session_name() ?

When to use session_id() ?

Which is the safest ?

In short session_name even if you do not define is generated so, as the session_id, none of them have to do with security, each represents this in the COOKIE sent at HTTP:

Set-Cookie: <NOME DA SESSÃO>=<ID DA SESSÃO>

So set create in your PHP like this:

<?php
session_name('foo');
session_id('baz');
session_start();

echo 'Hello world!';

In HTTP the answer will probably be similar to this:

HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Length: 12
Content-Type: text/html
Date: Wed, 10 Jan 2018 21:06:18 GMT
Keep-Alive: timeout=5, max=98
Set-Cookie: foo=baz; path=/

Hello world!

So session_name will be the cookie name and in the folder ./tmp a file with the name will be generated c:/php/temp/sess_baz, which is the same name as the ID.

  • William, I fully understand your explanation, and I thank you for all your attention! The only thing that became "vague" in the understanding, is where session_id() and session_regenerate_id() would enter the code, to be made the "validation" of it in the pages, or if I am getting something wrong...

  • @Raonibz regenerate ID changes the value of <ID DA SESSÃO> (in the example of the answer) by a random value. It is useful to prevent hijackings (which is not related to the problem), if you do this at all times

  • But the session_id, I don’t have to validate it to know that that Sesssion is really from the user ? Or it’s only used for the cookie ?

  • @Raonibz no session_id is used by the COOKIE to be able to know which TMP file or represents, as I explained in the reply in the part I speak "How the session works?"

  • Ah got it ! So really what will separate the Session_name systems from the Session_name ! session_id and session_regenerate_id would be an extra security if they capture the session, correct ?

  • @Raonibz actually the session_id that separates, session_name is to associate to the cookie, session_regenerate is only to generate a new ID (it will copy the data from one session to the other and I believe that GC will remove the old)

  • But if session_id is automatic, and separates the session_id, then it could not happen that both systems log in if the user is logged in to a single system.

  • 1

    @RBZ both, name or id, can be automatic, as they can be created by you, that’s relative, now what matters is that name is what associates to the cookie and id is the value associated to the file in the back end in the TMP folder. Not

  • If I were then to use session_id for session validation, I could for example use id_user and user to generate a md5 key like session_id, and validate using session_id === md5($uid.$uname), basically like this ?

  • @RBZ Do not do this please!! , this is complicated and probably unstable, use a value within $_SESSION['minhachave'] = array(token=>....) with hashs and compare afterwards $_SESSION['minhachave'][token] === outra origem

  • Opa tranquil !! rs Today, currently, the most used form which is ? Has how to make a style the "token" ?

  • The biggest problem is that the php documentation in this part is very weak, and you don’t find something very detailed, well explained why and how to use Sesssions in the best way, and some even using session_id in this way that I said...

  • @RBZ is no problem in PHP documentation, session has no exclusive focus on security, the use of Session is very varied, there are cases that does not even make sense to apply security, ie the documentation has no reason to explain of specific uses, since the focus is varied. The most used is relative, each one does in a way, however something without session that they use a lot is the Jwt, which is a 3rdparty service, if you want to understand the Jwt see: https://answall.com/q/155013/3635 - but it is because they use a lot that you must use, it is of your need.

  • 1

    Hell, it’s such a simple business deal that it’s hard to believe it’s "just that" you know !? kkkk But I understood perfectly, you got basically where I wanted to get, in the TOKEN, to be able to do a WS next to an APP. William thank you so much for your help and time! Thank you so much !

Show 9 more comments

1

First a session is a superglobal variable in array form, where you store data for a certain time.

According to the official documentation for session_id():

session_id() is used to obtain or define the session id for the current session.

And to session_name()

session_name - Fetches and/or sets the current session name

The difference of the two is in their purpose and a little in their operation, session_id is set once before logging in, and you will NOT need to call the method every time you need to use a session data, much of the session security comes from the function session_regenerate_id, and calling this method, you will generate a new identification for session without losing the data, however you will not be able to identify naturally which is each session, this is very useful for sessions open for a long time, because even if the identification is captured your identification will be modified during use.

To identify multiple sessions on the same server, the most feasible is the use of a session name, as this name will not interfere with your identifier and you can call anywhere any of the open sessionsdefined and yet remain governing the identifiers for the session.

References:

Basic use

Session ID

Session Regenerate ID

Session Name

  • Then the sequence to generate with the name and id would be: 1. session_name() 2. session_id() 3. session_start() correct ?

  • The session_id() I can use as id Anything (usually encrypted) correct !? But what is usually used ? Username ? How will it validate Session ? With the data you have in the global variable ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.