How to change the Session cookie value in Cakephp - php

In my Cakephp application, i have a session cookie with the name 'my_cookie' and it contains some random value 'QSD5111AS552DNJK'.
I observed that the value is same for the cookie (Before login and After login also). If i want to change the cookie value after login, what are the steps i have to follow.
And my code in core.php file
Configure::write('Session', array(
'defaults' => 'php',
'cookie' => 'my_cookie',
'timeout' => 4000
));
Please help me in this issue for getting more clarification.

I guess what you want to do is prevent session fixation, in that case it should be noted that CakePHP already does this for you out of the box. When using the authentication component, the session is being renewed before the authenticated user data is being written to it, and after the user data is being deleted on logout.
See
Source > AuthComponent::login()
Source > AuthComponent::logout()
For the sake of completeness, you can always renew the session manually, either via the session component in case you are in a controller
$this->Session->renew();
or by using the CakeSession class directly
App::uses('CakeSession', 'Model/Datasource');
CakeSession::renew();

Related

delete_cookies() helper not working in codeigniter 4

I want to create a remember me feature on my website using cookie.
when the user logout i want to destroy all session and cookies.
But the problem is i can't delete existing cookie.
i'am using CodeIgniter 4 framework
i already loaded cookie helper in my BaseController.
i tried this code in my logout controller :
delete_cookie('remember_me_token');
but that doesnt work, and also i tried this one :
set_cookie('remember_me_token', '', - 1209600); // set to minus
and the result is the same, i can't delete the cookie
please help :(
I followed up with a different approach using the setCookie function which was chained using the response and simply set the expiry time to -1.
$this->response->setCookie(['name' => 'token','value' => "" ,'expire' => '-1','domain' => $domain, 'path' => '/'])
Reference : https://codeigniter4.github.io/userguide/outgoing/response.html?highlight=set%20cookie

Laravel session id changes with each request

I have a Laravel 5.0 site where the frontend JS makes a lot of ajax calls to the backend Laravel code. I've noticed that on each ajax request I'm getting a new "laravel_session" cookie value in the response everytime. I'm guessing that this is some security mechanism to protect against session hijacking.
However I think this is causing an issue with my site, as my ajax calls often happen in parallel, not sequentially. I don't wait for the response before firing the next call.
Consider this scenario
. Ajax call 1 - request - laravel_session cookie = '1234'
. Ajax call 1 - response - laravel_session cookie = '2345'
. Ajax call 2 - request- laravel_session cookie = '2345'
. Ajax call 3 - request- laravel_session cookie = '2345'
. Ajax call 2 - response - laravel_session cookie = '3456'
. Ajax call 3 - response - session not longer valid
Is there any way around this?
I should also note that sessions are set to expire in the config/session.php as
'lifetime' => 120,
You are right it is a security mechanism. To disable it for testing, in Kernel.php comment out this line:
\App\Http\Middleware\EncryptCookies::class
Then you will see the session ID in your cookie viewer and it doesn't change.
You can Google for HTTP encrypted cookies to learn about the practice. There is an ongoing debate if this old practice is necessary now that we use HTTPS on every website.
Your domain is invalid. You need to look at config.session.domain and config.session.path.
The same issue happened with me and it was later identified that I was using
protected $middleware = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class
];
protected $middlewareGroups = [
'web' => [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class
]
]
in both $middleware and in $middlewaregroups because of which it was creating a new session id in movement between different routes.
I had the same issue, I tried a lot of solutions and nothing worked for me.
My case:
The token keeps changing on every request only when the session driver is set to database, and it works just fine on file and Redis driver.
After a lot of debugging, I found that the issue was not with session config, it was from the payload column in the session table in the DB.
I changed the payload column from text to longText, and it worked!
There are some important things about sessions. First is cookie time. If your Laravel app's timezone is UTC but your computer's timezone is +3 then if you set your cookie lifetime 120 (two hours) then cookie will deleted by browser immediatelly. You must increase your cookie lifetime.
Other option is encryption. Cookies are always encrypted. If you set encrypt=true in sessions.php file storage/framework/sessions folder will be encrypted. Sometimes this causes problem. If session doesn't keep then try to set encrypt to false. After that you can see session files are unencrypted and they have 'serialized' text. Then you can see your session variables in there.
Other option is domain variable in sessions.php file. You must set it correctly or leave it null. Domains must not have http(s):// at first. Write only domain in there (for example yourdomain.com, yourdomain.test, yourdomain.host, www.yourdomain.com, subdomain.yourdomain.com etc...).
Other option is about driver. If you set it to database then you must be sure your table columns have enough size for storing big session data. If you set it to file then you must be sure that storage/framework/sessionsĀ folder is writable and readable.
And there is a "small" (I think so important) trick. Don't use general keywords in session. For example don't use 'token' key. Use specific names for session. This is wrong: session(['token' => $result->token]), but this is better: session(['backend_remote_token' => $result->token])
Rock'n roll...

Cakephp Cookie gets deleted automatically when session timesout

I am writing a cookie for auto login users.
It works almost flaw less. But when the Session times out the cookie gets deleted, although it's set for 30 days.
I can't understand why this is happening.
If I close the browser and reopen it, all are fine, but if I leave the browser open and let the Session time out the cookie gets deleted to.
Configure::write('Session', array(
'defaults' => 'php',
'cookie' => 'KPD',
'timeout' => 180,
'cookieTimeout' => 30 * 1440
));
UPDATE: I found the problem but I don't have a solution! The problem is that when I rewrite the Cookie nothing happens, even if I try to delete it, and rewrite it.
I have a cookie as an array User.remember = array('token' => TOKEN). When I try to rewrite the token, the cookie remains the same!
Maybe you are not defining the value (in number of minutes) of Session.cookieTimeout, you should define proper value for Session.cookieTimeout. If it is not defined it will use the same value as Session.timeout

How to access php session files

I have a Yii application with cookie based login enabled.
So , every time a user connects to the application a session file gets created on the server
(/var/lib/php5) related to the PHPSESSID.
One of the Session variables is the timeout (timestamp).
I want to create a php script which access all of these Session files , opens them , checks for the timeout , and if it is timed-out ,make some changes to a specific table in the database.
First problem , from within my php script I'cant open session files in /var/lib/php5.
Permission denied.(AFAIK from my php script I try to open those files as Apache User , though I need to be superuser , how could that be done...on the fly ? -without changing file permissions)
Second problem.
Even if I try from my php script to open the superglobal $_SESSION for a specific session id
I still get the permission denied message.
$sSessId='la05bdm63rdmjevg4hfrcf17u6';
session_id($sSessId);
session_start();
print_r($_SESSION);
Any suggestions on how a php script can access those session files ?
Many thnx in advance.
First you do not need to invoke session_start() because by default its true, to disable in the config/main.php
'session' => array (
'autoStart' => false,// by default is true
),
The best way to read session in Yii is by using the build in functions Yii::app()->session which is similar to the super global array $_SESSION.
Yii::app()->session['var'] = 'value';
echo Yii::app()->session['var'];
To unset a session variable
unset(Yii::app()->session['var']);
To remove a session variable
Yii::app()->session->remove('var')
to change the path to your session variable
'session' => array (
'sessionName' => 'Site Access',
'cookieMode' => 'only',
'savePath' => '/path/to/new/directory',
),
Hope this will help

CakePHP keeps logging me out

Recently i have made three Cake Apps and all three share this problem. The config is mostly stock and i use this as the session options.
Configure::write('Session', array(
'defaults' => 'php',
'cookie' => 'test'
));
After lots of googling everyone just suggests that the security level is too high, but i have never changed this value, it's:
Configure::write('Security.level', 'medium');
Edit: I have also tried with low security and no change.
I am only using basic auth to check if the user is logged in or not.
After logging in the cookie is set to expire three hours later and the expire date doesn't update until I log in again, is this normal?
I cant seem to replicate the problem at all, sometimes I will log in and the very next click will log me out again and other times it will last a while.
I am using Chrome on Windows 7 and there is no AJAX on the website.
Any ideas? Thanks.
Are you using Ajax. Is the problem only happening in IE?
IE uses a different Browser Agent string for Ajax calls to the browser itself. For extra security, Cake checks the browser agent and, in the case of IE, thinks another browser is trying to hijack the session as the agent is different.
You can disable this check with:
Configure::write('Session.checkAgent', false);
After running into the same problem I've found that this was caused by the Session.cookieTimeout value. Although the php session was still valid, the expiration date on the session cookie does not get refreshed.
This is now my session config
Configure::write('Session', array(
'defaults' => 'php',
'timeout' => 30, // The session will timeout after 30 minutes of inactivity
'cookieTimeout' => 1440, // The session cookie will live for at most 24 hours, this does not effect session timeouts
'checkAgent' => false,
'autoRegenerate' => true, // causes the session expiration time to reset on each page load
));
the problem is with sessions:
First check ur 'phpinfo();'
check if the sessions are file based.
if yes, go through the process.
create a new script file(php) which contains only this code:<?php var_dump(session_save_path());?>
run it if you get null or empty string then go for this process:
first create a directory in your root folder name it 'xyz' or whatever u want.
make it writable i.e. chmod 777.
go to the script where you start sessions and before starting the sessions change your session_save_path to the newly created directory. i.e.: session_save_path('pathToxyz');
and then you r done.
if in case the sessions are set as memory: no configuration is required. they just use system memory. in that case you would never have got in to this problem.
You are not the only one having issues with CakePHP sessions on Chrome browser.
Pixelastic fellow coder suggests the following fix, quote :
Just create file named session_custom.php in app/config/, drop the following lines in it:
// Killing this config that was causing so much trouble with Chrome
ini_set('session.referer_check', '');
// No session id in url
ini_set('session.use_trans_sid', 0);
// Using custom cookie name instead of PHPSESSID
ini_set('session.name', Configure::read('Session.cookie'));
// Cookie like time, depending on security level
ini_set('session.cookie_lifetime', $this->cookieLifeTime);
// Cookie path
ini_set('session.cookie_path', $this->path);
Then set Configure::write('Session.save', 'session_custom'); in your core.php file.

Categories