cookie expiration time with activerecord session store - ruby-on-rails-3

This question is a follow-up to this. I can't seem to change the expiration time on the cookie when I switched to ActiveRecord session store. It contains just the session_id like it should, but its expiration time is set to HTTP session. I tried setting it in application.rb:
config.session_store :cookie_store, {
:expire_after => 2.hours,
}
But it doesn't do anything.
I could hack it by creating an additional cookie and storing a session_id there, but that seems wrong.

Nevermind, expiry of the cookie can be set by configuring ActiveRecord Session Store:
AppName::Application.config.session_store :active_record_store,
:key => 'your_cookie',
:expire_after => 2.hours

Related

Yii2 DbSession lost after redirect, 90% of the time

My login worked perfectly with PHP sessions. I tried switching to DbSession engine but login will not work anymore, as the session is empty after the page redirection.
Here's the workflow:
User enters his user id and clicks submit to post the data
Validation works (I tested) and a new identity cookie is created with the key sess = XXXX (tested with log just before redirect).
The $_SESSION is filled with the user data (tested with log just before redirect)
The page redirects with the new response cookie.
The password page loads and the request cookie has the same XXXX value (tested with log just after redirect + in chrome developer tools).
The session now only contains
[__flash] => Array
(
)
response cookie "sess" = request cookie "sess" = id in the session table, so the same key is everywhere, yet the session is still empty on the password page, 90% of the time (because in some random cases, the session is still there, but I can't reproduce it on demand)
I already checked these questions, not the same problem:
PHP session lost after redirect
Session lost after redirect in Codeigniter
Has anyone seen something similar before? I can't figure out what's causing this.
Addendas:
Session configuration
'session' => [
'class' => 'yii\web\DbSession',
'name' => 'sess',
'timeout' => 3600,
'db' => 'session_db',
'sessionTable' => 'session',
],
Session db config
$config['components']['session_db'] = [
'class' => 'yii\db\Connection',
...
],
Login action
// authenticate() Just checks if the user is valid, etc
Yii::$app->user->authenticate();
// login() just calls parent::login(), sets some session values then returns !$this->getIsGuest()
Yii::$app->user->login(Yii::$app->user);
update!! I have just noticed that if I use the same database instead of "db" (my main db) instead of "session_db", it works perfectly, even if both tables have exactly the same schema in the 2 databases.

RESTful API using JWT (JSON Web Token) setup token expiry

I'm using JWT for RESTful API (Laravel Web-Services for mobile). How to setup token expiry to never expiry or what the best practice to setup token expiry?
Because currently i need to get the token everytime when the token expired, can anybody have this issue or best solution for token expiry.
There is nothing to make the token never expire. However you can extend the expiration date to a very huge time span, 1 year for example. This is possible, however it is not recommended for security.
In order to achieve that, you need to configure two parts, the token refresh time, and token expiry.
So in config/jwt.php
'refresh_ttl' => 29030400, // Number of minutes in 1 year (12*4*7*24*60*60)
And when you are creating your token, you can pass something like the following
$tokenId = base64_encode(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
$issuedAt = Carbon::now()->timestamp;
$notBefore = $issuedAt; //Adding 10 seconds
$expire = $notBefore + 12*4*7*24*60*60; // Adding 6 hours
/*
* Create the token as an array
*/
$data = [
'iat' => $issuedAt, // Issued at: time when the token was generated
'jti' => $tokenId, // Json Token Id: an unique identifier for the token
'iss' => 'https://example.com', // Issuer
'nbf' => $notBefore, // Not before
'exp' => $expire, // Expire
'data' => [ // Data related to the signed user
'userId' => Auth::user()->id, // userid from the users table
]
];
Now, your token will never expire before 1 year. And you have up to 1 year to refresh it. When the user opens the application the next time, and you authenticate the token, you can refresh it. You can refresh the token, as mentioned in the documentation here. I would recommend going through this laracasts discussion as well.
Also, I have found this question on StackOverflow, I think it will help.

MVC 4 Forms Authentication (Infinite Login)

I was surprised I couldn't find a good answer to this out on the interwebz, so here we are.
I'm setting a FormsAuthenticationTicket to expire after a week. This is used in tandem with a "Remember Me" setting we feature on our login form. This is being accomplished by :
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
// set the auth token expiration to a week
var authTicket = new FormsAuthenticationTicket(1, user.Email, DateTime.Now, DateTime.Now.AddHours(168), true, userData);
var encryptedTicket = FormsAuthentication.Encrypt(authTicket);
cookie.Value = encryptedTicket;
cookie.Expires = authTicket.Expiration;
With this, I've also extended our session timeout, as many of our users keep the application open for equally long periods of time :
<forms loginUrl="~/account/sign-in" timeout="10080" name="t5S4U4Y152" domain=".xxxxxxx.xxx.xxxxx"/>
My question :
I've been asked to make this a non-expiring cookie, such that as long as the user retains it, they'll always be logged in - more or less an infinite login. Is there a default value I can set the ticket and timeout to in order to achieve this?
Yes, I could set both expiration's to something like 50 years from the present, but I'm wondering if there is a cleaner or more suitable approach?
No there isn't any value you can set the expiration so it is infinite. You'll just need to set it to something really long.
As you know, if you do not set an expiration the cookie then only lives for the length of the session (when the browser is closed), which is definitely not what you want.
You can also use slidingexpiration=true so that whenever a user comes back to the site, the expiration date on the cookie is refreshed to be Today + Timeout instead of DateInitiallyIssued + Timeout

My Salesforce password changed and now my Ruby on Rails app is broken

I have a simple demo app set up to be able to access Salesforce.com from a Ruby on Rails app. My code is extremely simple:
def sign_in_salesforce
client = OAuth2::Client.new(ENV['SALESFORCE_CONSUMER_KEY'], ENV['SALESFORCE_CONSUMER_SECRET'], :site => 'https://login.salesforce.com/', :authorize_url => 'services/oauth2/authorize', :token_url => 'services/oauth2/token')
auth_url = client.auth_code.authorize_url(:redirect_uri => 'https://99.44.242.76:3000/users/oauth_callback')
redirect_to auth_url
end
I then have a method to take care of the callback.
def oauth_callback
db_client = Databasedotcom::Client.new
db_client.authenticate(:token => params[:code])
puts db_client.inspect
end
The error in the console is:
ArgumentError (ArgumentError):
app/controllers/users_controller.rb:60:in `oauth_callback'
The line that is causing the error is:
db_client.authenticate(:token => params[:code])
like the token that I am getting is invalid or something.
It worked fine until I changed my Salesforce password (which they required me to do). What am I missing? Thanks for the help.
If the response you receive is that your refresh token is no longer valid then you need to restart the OAuth process from scratch to obtain a new refresh token; you can then use to get new session tokens in subsequent uses of the app as you have been up until now.
Essentially, start the process as you would for the very first time the app is launched.

For every request a new session is getting generated in Yii application

I know I am either skipping something or configured session incorrectly but Yii sessions are not working for me. I have spent a lot of time in debugging and searching but it doesn't result in any concrete answer.
As described in documentation as well as tutorials over internet I have configured my application session as follows:
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
'session' => array (
'sessionName' => 'Site Session',
'class'=>'CHttpSession',
'useTransparentSessionID' =>($_POST['PHPSESSID']) ? true : false,
'autoStart' => 'true',
'cookieMode' => 'allow',
'timeout' => 300
),
However each time I am sending a request to server, I get a new session object. I have verified same via echo "Session id: ".Yii::app()->session->sessionID;, every time it gives me different id. Also variables which I have added in session previously are not accessible due to this behaviour.
Kindly provide some pointers, I have spent more than 4 hours in debugging and looking for a solution. Tons of thanks for any pointers in advance.
Thanks
~Tarun
It could well be just that you have a space in your sessions name.
I've just done a quick test on my working Yii instance, changed the session name to have a space in it, and the cookie value for the session seems to change every time.
Please read php session name documentation at this url http://php.net/manual/en/function.session-name.php
It clearly mentions that session name should contain only alphanumerical characters. That too it should contain at least one alphabet(session name cannot have all its characters as digits also). Otherwise a new session id is generated every time.
chrome 44 and chrome 47's bug , update it to 51,It's ok.
Just a note cause I ran into this issue in Yii2. I had a constant COOKIE_DOMAIN that was set via php-fpm config and it was for the wrong domain name, causing the session to reset. Make sure this is set to ".example.com" (including the . at the start to support all your hostnames)
'components'=>[
'session' => [
'class' => 'yii\web\DbSession',
'cookieParams' => [
'path' => '/',
'domain' => COOKIE_DOMAIN, // <<<--- check this
'secure' => true,
],
'writeCallback' => function($session){
return [
'user_id' => Yii::$app->user->id
];
},
'sessionTable' => 'session', // session table name. Defaults to 'session'.
],
...
]