Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session in Rails_API gem

I am using the rails_api gem in my project. I want to add session management for authentication, but it seems the session does not work. Here is my configuration in config/initializer/session_store.rb:

Pmcapi::Application.config.session_store :cookie_store, {

  key: '_pmcapi_session', 
  expire_after: 1.hour
}

I added config.api_only = false in application.rb (Adding cookie session store back to Rails API app)

and in my session_controller, I added session to store the token

# session_controller.rb
def create
  #just to generate new token
  user.reset_sso_token!
  session[:token] ||= user.sso_token
  self.current_user = user
  redirect_to root_path
end

When in application_controller, I want to access session[:token] but the result is nil:

# application_controller.rb
def authenticate_user!
  #puts("User Authentication")
  #puts(request.authorization)
  #puts(request)
  @user = User.authenticate_with_token(session[:token])
  #head :unauthorized unless @user.present?
  redirect_to sign_in_path if @user.nil?
end
like image 839
Ari Firmanto Avatar asked Sep 24 '13 00:09

Ari Firmanto


1 Answers

from what I can see from your config.api_only = false line this basically makes rails use the full stack rather than keeping it slim, which is the main reason you could be using rails-api So I suggest trying something like

config.middleware.use Rack::Session::Cookie

in your application controller.

If that doesn't work I recommend drawing your attention to This pull request about session management in the rails 4 stack

like image 142
Grant Avatar answered Nov 03 '22 21:11

Grant