2
2

More than 5 years have passed since last update.

Rails4のdevise3.5.xのENV['DEVISE_SECRET_KEY']について

Last updated at Posted at 2015-11-04

はじめに

この記事はrails4におけるdevise v3.5.xでのENV['DEVISE_SECRET_KEY']の有無について書いたものです。

確認済み環境

gem 'rails', '4.2.4'
gem 'devise', '3.5.1' # '3.5.2'も

DEVISE_SECRET_KEYは指定必須か?

ENV['DEVISE_SECRET_KEY']を定義してる時と、ミスって定義し忘れた場合も変わらず正常に動いていたので、指定必須じゃないの?どーなってんの?と思ったのが事の発端。

補足:
DEVISE_SECRET_KEYとは、config/initializers/devise.rbに下記の様に、誰かが書き始めたことによって稀に検索される環境変数名。

config.secret_key = ENV['DEVISE_SECRET_KEY']

結論

DEVISE_SECRET_KEY( or config.secret_key)は指定してもしなくてもいい!

deviseの挙動としては、下記の様になってると言っているので、

Devise.setup do |config|
  # ENV['DEVISE_SECRET_KEY']が未定義なら、ENV['SECRET_KEY_BASE']を利用する
  config.secret_key = ENV['DEVISE_SECRET_KEY'] || ENV['SECRET_KEY_BASE']
end

production環境でもSECRET_KEY_BASEさえ設定されていれば後は気にしなくていい。

確認方法

下記を実行すると、

$ bundle exec rails g devise:install

config/initializers/devise.rbが生成され、

そこに真理が書かれてた。

Devise.setup do |config|
  # The secret key used by Devise. Devise uses this key to generate
  # random tokens. Changing this key will render invalid all existing
  # confirmation, reset password and unlock tokens in the database.
  # Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key`
  # by default. You can change it below and use your own secret key.
  # config.secret_key = '5b82d6c79aa93c1b06...'

  # 基本的にはRails4+のsecret_key_baseを再利用するんだけど、
  # deviseのconfig.secret_keyを定義した場合は、そっちを優先的に使うよ。
  #..
end

まとめ

結果、DEVISE_SECRET_KEYが未定義の場合は、railsのSECRET_KEY_BASEを再利用するんだとわかり、取り敢えずスッキリ。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2