简体   繁体   中英

Rails : API : Devise : current_user nil

I'm developing a Rails API and using Devise for authentication.

When I use current_user in controllers it always returns nil (as if there is no signed in user) although the user was already signed in.

Why it did work while developing a website and didn't work while developing an API?

I am using the curl commands to test the application:

sign in:

curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST http://localhost:3000/api/v1/sessions -d "{\"user\":{\"email\":\"user1@example.com\",\"password\":\"secret123\"}}"   

sign out :

curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X DELETE http://localhost:3000/api/v1/sessions/\?auth_token\=JRYodzXgrLsk157ioYHf

Are you namespacing any of your controllers?

ie:

I have:

namespace :api, defaults: { format: :json } do

devise_for :users, controllers: {

  registrations: 'api/registrations',
  sessions:      'api/sessions'
}

end

in my routes.rb

I wanted to use #current_user and #user_signed_in? methods that Devise supposedly provides, yet kept getting 'nil' and undefined_method errors

Did some reading on namespacing and realized that devise has a lot of magical powers. Since I namespaced my users within an api, Devise generated: current_api_user & api_user_signed_in? methods for me. These did not return nil

You can read more about it here: https://github.com/plataformatec/devise/blob/master/lib/devise/rails/routes.rb#L61

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM