I'm working on a web app using Slim, but I'm facing an issue with setting and persisting sessions.
Here is my index.php. I am trying to set a csrfToken key in the $_SESSION array, so that every request that is made through the app checks if the user has a csrfToken key, if not it will create one.
I'm just confused as to why it isn't persisting because on the next request it's gone. session_start is being called, it's being called automatically by '\Slim\Middleware\SessionCookie'.
Any ideas why this wouldn't be working? And would it be better to place this into middleware or use a hook?
use duncan3dc\Laravel\Blade;
use duncan3dc\Helpers\Env;
# TODO: Bootstrap the app. Move this to a seperate file. Dev only.
R::setup('mysql:host=localhost;dbname=somedb','user','pass');
$app = new \Slim\Slim(array(
'mode' => 'development',
'templates.path' => './views',
'cookies.encrypt' => true,
'cookies.secret_key' => 'mylongsecretkey',
'cookies.cipher' => MCRYPT_RIJNDAEL_256,
'cookies.cipher_mode' => MCRYPT_MODE_CBC
));
$app->add(new \Slim\Middleware\SessionCookie(array(
'expires' => '10 minutes',
'path' => '/',
'domain' => 'site.com',
'secure' => false, # Contact client to discuss using SSL
'httponly' => false,
'name' => '_sus',
'secret' => 'mylongsecretkey', # Do I need this twice?
'cipher' => MCRYPT_RIJNDAEL_256,
'cipher_mode' => MCRYPT_MODE_CBC
)));
# Not persisting ...
if(!isset($_SESSION['csrfToken']))
$_SESSION['csrfToken'] = hash("sha512",mt_rand(0,mt_getrandmax()));
# TODO: Bootstrap these.
require 'routes/index.php';
require 'routes/dashboard.php';
require 'routes/signup.php';
require 'routes/contactus.php';
require 'routes/privacypolicy.php';
require 'routes/testimonials.php';
require 'routes/login.php';
$app->run();
I figured out how to do it after reading more into hooks.
$app->hook('slim.before.router', function() use ($app){
if(!isset($_SESSION['csrfToken']))
$_SESSION['csrfToken'] = hash("sha512",mt_rand(0,mt_getrandmax()));
});
Related
I am writing and application in Slim Framework v3.1. I am a lot confused on how to correctly set and get the cookies using Slim's methods.
I need your help in understanding what is the right way to read and write cookies with encryption enabled.
I also need to know how to enable encryption and decryption for the same.
Currently my $app is initialised this way -
$settings = require __DIR__ . '/../src/settings.php';
$app = new \Slim\App($settings);
My settings.php looks like below -
return [
'settings' => [
'displayErrorDetails' => true, // set to false in production
'addContentLengthHeader' => false, // Allow the web server to send the content-length header
// Renderer settings
'renderer' => [
'template_path' => __DIR__ . '/../templates/',
],
// Cookies Encryption
'cookies.encrypt' => true,
'cookies.secret_key' => '53cr3t',
'cookies.cipher' => OPENSSL_CIPHER_AES_256_CBC,
'cookies.cipher_mode' => MCRYPT_MODE_CBC,
],
];
I want a "remember-me" cookie for my login form and get it work until I reopen the browser. I am using the Zend Framework 2 to get it done.
I set up a form with a checkbox and have this in my controller after validating the form:
$userSession = new Container("test");
$sessionManager = $userSession->getManager();
$sessionManager->rememberMe(1209600);
$sessionManager->start();
In the module.config.php I have the following settings for the session:
'session' => array(
'name' => 'Test_SESSION',
'save_path' => realpath('C:\xampp\htdocs\Workspace\test\data\session'),
'remember_me_seconds' => 1209600,
'cookie_lifetime' => 1209600,
'use_cookies' => true,
'cookie_httponly' => true,
),
And finally in module.php:
$session = new SessionConfig();
$session->setOptions($this->serviceLocator->get("config")["session"]);
I searched through the web for any advises and tried something, but at least when I close the browser the cookie is deleted. Firefox settings of deleting cookies were checked also, so they won't be automatically deleted. Does any one has a successful solution or hint?
Edit: When I take the code of newtake and add $sessionManager->rememberMe(); to it, the session is still alive after closing browser, but I can't login anymore even the login process is successfully done. Anyone heard from this curiosity?
Need setup SessionConfig to SessionManager. It is my config
'service_manager' => array(
'factories' => array(
'Zend\Session\SessionManager' => function ($sm) {
$sessionConfig = new \Zend\Session\Config\SessionConfig();
$sessionConfig->setOptions([
'use_cookies' => true,
'gc_maxlifetime' => 1728000,
'cookie_lifetime' => 1728000,
'name' => 'COOKIE_NAME',
]);
$sessionManager = new \Zend\Session\SessionManager($sessionConfig);
$sessionManager->start();
return $sessionManager;
}
)
)
I am using laravel with the thujohn/twitter package.
But i want whenever any use registered they will provide us CONSUMER_KEY and CONSUMER_SECRET and we will use that details to post the tweet,favorites tweet etc.
But in the thujohn/twitter package the CONSUMER_KEY and CONSUMER_SECRET is set one time and that will use for all users and i want to use each register user will use their own consumer details.
Any one know any solution on the same
Looking at the source code you have the reconfigure method:
/**
* Set new config values for the OAuth class like different tokens.
*
* #param Array $config An array containing the values that should be overwritten.
*
* #return void
*/
public function reconfig($config)
{
// The consumer key and secret must always be included when reconfiguring
$config = array_merge($this->parent_config, $config);
parent::reconfigure($config);
return $this;
}
So you can pass an array with the configs you want:
Twitter::reconfigure([
'consumer_key' => '',
'consumer_secret' => '',
'token' => '',
'secret' => '',
]);
This configs will then be passed to the parent which is another library called tmhOAuth here's the code for that:
public function reconfigure($config=array()) {
// default configuration options
$this->config = array_merge(
array(
// leave 'user_agent' blank for default, otherwise set this to
// something that clearly identifies your app
'user_agent' => '',
'host' => 'api.twitter.com',
'method' => 'GET',
'consumer_key' => '',
'consumer_secret' => '',
'token' => '',
'secret' => '',
// OAuth2 bearer token. This should already be URL encoded
'bearer' => '',
// oauth signing variables that are not dynamic
'oauth_version' => '1.0',
'oauth_signature_method' => 'HMAC-SHA1',
// you probably don't want to change any of these curl values
'curl_http_version' => CURL_HTTP_VERSION_1_1,
'curl_connecttimeout' => 30,
'curl_timeout' => 10,
// for security this should always be set to 2.
'curl_ssl_verifyhost' => 2,
// for security this should always be set to true.
'curl_ssl_verifypeer' => true,
// for security this should always be set to true.
'use_ssl' => true,
// you can get the latest cacert.pem from here http://curl.haxx.se/ca/cacert.pem
// if you're getting HTTP 0 responses, check cacert.pem exists and is readable
// without it curl won't be able to create an SSL connection
'curl_cainfo' => __DIR__ . DIRECTORY_SEPARATOR . 'cacert.pem',
'curl_capath' => __DIR__,
// in some cases (very very odd ones) the SSL version must be set manually.
// unless you know why your are changing this, you should leave it as false
// to allow PHP to determine the value for this setting itself.
'curl_sslversion' => false,
'curl_followlocation' => false, // whether to follow redirects or not
// support for proxy servers
'curl_proxy' => false, // really you don't want to use this if you are using streaming
'curl_proxyuserpwd' => false, // format username:password for proxy, if required
'curl_encoding' => '', // leave blank for all supported formats, else use gzip, deflate, identity etc
// streaming API configuration
'is_streaming' => false,
'streaming_eol' => "\r\n",
'streaming_metrics_interval' => 10,
// header or querystring. You should always use header!
// this is just to help me debug other developers implementations
'as_header' => true,
'force_nonce' => false, // used for checking signatures. leave as false for auto
'force_timestamp' => false, // used for checking signatures. leave as false for auto
),
$config
);
}
I'm trying to make a post request to the same subdomain with GuzzleHttp in a Laravel 5.1 installation, but as a response the login page is returned, showing that a new Session has been created in the request. The current session is not affected.
Why does Laravel create a new session?
In session.php I have the following values:
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => 120,
'expire_on_close' => true,
'files' => storage_path('framework/sessions'),
'cookie' => 'admin_mydomain_com_session',
'path' => '/',
'domain' => 'admin.mydomain.com',
'secure' => false
In my controller I use the following code to make the request:
// Create headers
$headers = array(
'X-CSRF-Token' => csrf_token()
);
// Create data
$data = array(
'param' => 'param',
'_token' => csrf_token()
);
// Create a POST request
$client = new Client();
$res = $client->request('POST', 'http://admin.mydomain.com/my-url',
array(
'headers' => $headers,
'form_params' => $data
)
);
$statusCode = $res->getStatusCode();
$body = $res->getBody();
echo $body; // Shows me the login page
The answer is really to understand how sessions work. When you make a request via a browser lets say, the response issued by the server will include a cookie with a session id. That id is what identifies you to the server. When you navigate a site through your browser the request it issues includes the cookies.
So when your creating a request via Guzzle your leaving out the cookie from the previous response. Hence the server will always create a new session id for you.
I use this library : Oauth2 PHP
I can't find the setting to change the expiration time, I tried:
new OAuth2\Server($this->_mem, array('use_jwt_access_tokens' => true, 'access_token_lifetime' => 2419200));
But the lifetime of the token is always 3600. What's the right setting?
Edit: As suggested, I tried to use refresh token
new OAuth2\Server($this->_mem, array('use_jwt_access_tokens' => true, 'always_issue_new_refresh_token' => true));
The client_credential grant type + JWT bearer works but I never get a refresh token (only access token). Even upon token verification, I never get a refresh token.
Edit: Since the refresh doesn't work for me, as suggested I tried to set the token expiration time doing
new OAuth2\Server($this->_mem, array('use_jwt_access_tokens' => true, 'access_lifetime' => 12000));
The response upon client credential still returns a short token
{ ["access_token"]=> string(648) "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpZCI6ImU0NjE0MzdhMjY2YjFkNWY0OWU5MDY5MjQwODg5NjU0MDI2ZGRmODAiLCJpc3MiOiIiLCJhdWQiOiI4OWM2MjRmNTNiYTVmOTM3NjFmZWFhNmU1MGI1ZDk1NGQ4ZGRjMTIxIiwic3ViIjpudWxsLCJleHAiOjE0MzQ0NjI2NDIsImlhdCI6MTQzNDQ1OTA0MiwidG9rZW5fdHlwZSI6ImJlYXJlciIsInNjb3BlIjoicHVibGljIHJlYWRfbmV3cyJ9.Mk_KyUk_8yPnq9eEjvgVOJXBOkQSifAPbEaUvY4X9WvfmImPnC7PJx_99ODpiJR_gMLhZ3gBl1gQEJ2z6xUZ83dntCYzGWumkVLNpJG8omuVkmZqNnbLYYXl-vzmGOblceeDrKw_lrXc4rb72BeFaMeZWwFV7YMrgA0LOsYyZmAiDblcbHtpPGpUd2EC3y7VxLnyA8u07eY4aswOHwClPlDwHX_HwfMUmDLWkoTcrRf1AvKn-cnj41eL0SU9AJHWab8AOK7lxDsaqnits5pXj--cG9hr8pWOsFPQ2D9qYOsMvbEOi4zDJEdaIp-qvzn6N5Wrm5GxdbU1AqwvM531hQ" ["expires_in"]=> int(3600) ["token_type"]=> string(6) "bearer" ["scope"]=> string(16) "public" }
It appears it was a cache issue, the token is now set to the proper expiration length/time
You can change the access_token lifetime using the access_lifetime OAuth2\Server config parameter from examining the code.
The access_lifetime config parameter is used in creating the token in OAuth2\ResponseType\JwtAccessToken line 63:
$expires = time() + $this->config['access_lifetime'];
This can be set when instantiating the server which takes the following config parameters as listed in OAuth2\Server lines 109 - 126.
// merge all config values. These get passed to our controller objects
$this->config = array_merge(array(
'use_jwt_access_tokens' => false,
'store_encrypted_token_string' => true,
'use_openid_connect' => false,
'id_lifetime' => 3600,
'access_lifetime' => 3600,
'www_realm' => 'Service',
'token_param_name' => 'access_token',
'token_bearer_header_name' => 'Bearer',
'enforce_state' => true,
'require_exact_redirect_uri' => true,
'allow_implicit' => false,
'allow_credentials_in_request_body' => true,
'allow_public_clients' => true,
'always_issue_new_refresh_token' => false,
'unset_refresh_token_after_use' => true,
), $config);
There is also support for refresh tokens according to the code for Server.php and JwtAccessToken.php.
In server.php (where you are passing grant type and client credentials)
$config = array(
'access_lifetime' => 86400
);
$server = new OAuth2\Server($storage, $config);
source: https://github.com/bshaffer/oauth2-server-php/issues/699