DEV Community

Can Olcer
Can Olcer

Posted on • Originally published at canolcer.com

5

Rails: Prevent users from logging out after each deployment

Here's a quick one, and it may be obvious to some of you but I didn't know about it. I noticed that my Rails app (Fugu) kept logging out all users after every deployment.

First, I thought it's an issue with Devise, but it turns out that it's related to a variabled called secret_key_base that Rails uses to sign and encrypt cookies (among other things).

For production, there are multiple places to define secret_key_base. A glance at the Rails soure code shows that Rails looks for it in ENV["SECRET_KEY_BASE"], credentials.secret_key_base, or secrets.secret_key_base.

In my case, I hadn't set up any credentials or secrets, nor was I providing an environment variable.

Digital Ocean (and, as it looks, Heroku) automatically sets the SECRET_KEY_BASE environment variable for you, and it changes with every deployment. And this was the problem. After each deployment, my Rails app couldn't decrypt the existing session cookies anymore beause secret_key_base had a different value, and my users needed to log in again.

To solve the problem, just provide a SECRET_KEY_BASE environment variable in your production server. The simplest way to generate it is to run rake secret in your terminal (make sure you're in a Rails project folder).

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (2)

Collapse
 
sag profile image
Sagar Gupta

TIL something new! Thank you :)

Collapse
 
canolcer profile image
Can Olcer

You're welcome!

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay