Getting Started
suggest changeCreate a Rails project and set up Devise.
rails new devise_example
Add Devise to the Gemfile at the project root:
gem 'devise'
Then run bundle install.
Next, run the generator:
rails generate devise:install
The generator prints a few setup steps. Follow them.
Generate a Devise model:
rails generate devise MODEL
Then run rails db:migrate (or rake db:migrate on Rails 4).
For more details, see the Devise gem.
Authentication Token
An authentication token identifies a user without a session. Add the column before writing the filter. This example stores the token in auth_token. The model attribute, the column, and params must use that same name. Devise's old :token_authenticatable module is not part of current Devise; this check is application code.
rails g migration add_authentication_token_to_users
class AddAuthenticationTokenToUsers < ActiveRecord::Migration
def change
add_column :users, :auth_token, :string
add_index :users, :auth_token, unique: true
end
end
Leave the default unset. default: "" with a unique index lets only one user have a blank token, so the second insert fails. Assign a real token before authenticating. secure_compare needs two strings of the same length.
Then run the migration.
In app/controllers/application_controller.rb, add:
respond_to :html, :json
This lets the application respond with HTML or JSON.
Then:
protect_from_forgery with: :null_session
:null_session is the API strategy. It empties the session for the request instead of raising when the CSRF token is missing. :null is not a valid strategy.
Add an authentication filter. Devise still treats email as the login field here; the token is checked beside it.
before_action do
user_email = params[:user_email].presence
user = user_email && User.find_by(email: user_email)
if user && Devise.secure_compare(user.auth_token, params[:auth_token])
sign_in user, store: false
end
end
before_filter is the old name. It was removed in Rails 5.1; use before_action.
The filter above is only an example.
store: false stops Devise from writing a session cookie, so the request stays stateless.