9

I would like to access the Rails session secret programmatically (I am using it to generate a sign-on token).

Here's what I've come up with:

ActionController::Base.session.first[:secret]

This returns the session secret. However, every time you call ActionController::Base.session it adds another entry to an array so you end up with something like this:

[{:session_key=>"_new_app_session", :secret=>"totally-secret-you-guys"}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]

This strikes me as being no good.

Is there a better way to access the session secret?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Luke Francl
  • 31,028
  • 18
  • 69
  • 91

5 Answers5

12

For Rails4

Rails.configuration.secret_token
Rails.configuration.secret_key_base

For Rails3

Rails.configuration.secret_token

But if for Rails2.x, like Don Parish mentioned

ActionController::Base.session_options[:secret]
choonkeat
  • 5,557
  • 2
  • 26
  • 19
4

Thanks, Jake.

Since the secret doesn't change based on the request or the action, this also works:

ActionController::Base.session_options_for(nil,nil)[:secret]
Luke Francl
  • 31,028
  • 18
  • 69
  • 91
2
ActionController::Base.session_options_for(request,params[:action])[:secret]
whoisjake
  • 622
  • 4
  • 7
1

For Rails 2.3, I've used:

ActionController::Base.session_options[:secret]
0

For Rails 3, Rails.configuration is same to Rails.application.config, so Rails.configuration.secret_token acts just as what choonkeat provided.

James Chen
  • 10,794
  • 1
  • 41
  • 38