开发者

How to destroy session ("logout") with token-authenticated users

开发者 https://www.devze.com 2023-03-18 20:36 出处:网络
For Devise user models that use :token_authenticatable, like so class Voter < ActiveRecord::Base devise :token_authenticatable

For Devise user models that use :token_authenticatable, like so

class Voter < ActiveRecord::Base
  devise :token_authenticatable
end

there used to be a route called destroy_user_session, so that you could log users out by linking to destroy_user_session_path. This seems to have changed in recent versions -- now only :database_authenticatable creates a destroy route for me.

So for users that use token authentication, what is the proper way to implement a "log out"/"sign out"开发者_运维百科 action to end their sessions?


By default, when you sign in via token, Devise will store the user in session just like in the database authentication strategy.

You can disable this by setting stateless_token to true in the Devise initializer:

Devise.setup do |config|
  config.stateless_token = true
end

This way, the token must be provided with every request.


As I understand it, token authentication was designed to be used together with database authentication. devise_for will only add the session routes if your model is database_authenticatable. This seems like a minor oversight on Devise's part, but in my opinion, access tokens leaving the user in session doesn't make much sense to me to begin with.

Anyway, try to define the routes to Devise's sessions manually.

Adapted from Devise's routing helpers (untested code):

as :user do  # User scope
  resource :session, :controller => 'devise/sessions' do
    # new_user_session | GET /users/sign_in => devise/sessions#new
    get :new, :path => 'sign_in', :as => "new"

    # user_session | POST /users/sign_in => devise/sessions#create
    post :create, :path => 'sign_in'

    # destroy_user_session | GET /users/sign_out => devise/sessions#destroy
    get :destroy, :path => 'sign_out', :as => "destroy"
  end
end

In any case, the documentation for the devise_for helper specifies which routes are created and what they point to.

0

精彩评论

暂无评论...
验证码 换一张
取 消