设计令牌身份验证在登录时不返回令牌

Devise token auth not returning token on sign in

我已按照教程进行操作 here and here

我可以创建一个用户并从 sign_in 获得成功响应,但该登录不包含要在未来请求中使用的访问令牌。

我还可以确认正在创建令牌并将其保存在数据库中。

注册请求

curl -XPOST -H 'Content-Type: application/json' -d '{"email":"test@gmail.com", "password":"12345678"}' http://localhost:3000/auth   

Returns

{
    "status": "success",
    "data": {
        "id": 3,
        "provider": "email",
        "uid": "test@gmail.com",
        "allow_password_change": false,
        "name": null,
        "nickname": null,
        "image": null,
        "email": "test@gmail.com",
        "created_at": "2020-08-04T17:42:08.252Z",
        "updated_at": "2020-08-04T17:42:08.311Z"
    }
}  

有服务器日志

Started POST "/auth" for ::1 at 2020-08-04 13:42:07 -0400
   (0.4ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by DeviseTokenAuth::RegistrationsController#create as */*
  Parameters: {"email"=>"test@gmail.com", "password"=>"[FILTERED]", "registration"=>{"email"=>"test@gmail.com", "password"=>"[FILTERED]"}}
Unpermitted parameter: :registration
Unpermitted parameter: :registration
Unpermitted parameter: :registration
   (0.1ms)  BEGIN
  User Exists? (0.6ms)  SELECT 1 AS one FROM "users" WHERE "users"."email" =  AND "users"."provider" =  LIMIT   [["email", "test@gmail.com"], ["provider", "email"], ["LIMIT", 1]]
  User Create (0.4ms)  INSERT INTO "users" ("uid", "encrypted_password", "email", "created_at", "updated_at") VALUES (, , , , ) RETURNING "id"  [["uid", "test@gmail.com"], ["encrypted_password", "a$uJH9U37sHe5QZoIHCrx5mOwhJgkIRCEf9HEXHghdCoY4bpyvNUCEu"], ["email", "test@gmail.com"], ["created_at", "2020-08-04 17:42:08.252960"], ["updated_at", "2020-08-04 17:42:08.252960"]]
   (0.5ms)  COMMIT
   (0.2ms)  BEGIN
  User Update (0.3ms)  UPDATE "users" SET "tokens" = , "updated_at" =  WHERE "users"."id" =   [["tokens", "\"{\\"QcLhZ_VfotCzRhOPxzEsSg\\":{\\"token\\":\\"a$IWfMusQGsXHxJYYa555BDOd7d5g6jkfUVguMpjvtL4yKD8tFmldIm\\",\\"expiry\\":1597772528}}\""], ["updated_at", "2020-08-04 17:42:08.311049"], ["id", 3]]
   (0.7ms)  COMMIT
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" =  LIMIT   [["id", 3], ["LIMIT", 1]]
Completed 200 OK in 324ms (Views: 0.2ms | ActiveRecord: 7.6ms | Allocations: 32282)

登录请求

curl -XPOST -H 'Content-Type: application/json' -d '{"email":"test@gmail.com", "password":"12345678"}' http://localhost:3000/auth/sign_in

Returns

{
    "data": {
        "id": 3,
        "email": "test@gmail.com",
        "provider": "email",
        "uid": "test@gmail.com",
        "allow_password_change": false,
        "name": null,
        "nickname": null,
        "image": null
    }
}

有服务器日志

Started POST "/auth/sign_in" for ::1 at 2020-08-04 13:43:58 -0400
Processing by DeviseTokenAuth::SessionsController#create as */*
  Parameters: {"email"=>"test@gmail.com", "password"=>"[FILTERED]", "session"=>{"email"=>"test@gmail.com", "password"=>"[FILTERED]"}}
Unpermitted parameter: :session
Unpermitted parameter: :session
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."email" =  AND "users"."provider" =  LIMIT   [["email", "test@gmail.com"], ["provider", "email"], ["LIMIT", 1]]
Unpermitted parameter: :session
Unpermitted parameter: :session
   (0.1ms)  BEGIN
  User Update (0.3ms)  UPDATE "users" SET "tokens" = , "updated_at" =  WHERE "users"."id" =   [["tokens", "\"{\\"QcLhZ_VfotCzRhOPxzEsSg\\":{\\"token\\":\\"a$IWfMusQGsXHxJYYa555BDOd7d5g6jkfUVguMpjvtL4yKD8tFmldIm\\",\\"expiry\\":1597772528},\\"8LPS7V6YRe16JVDjErFUvA\\":{\\"token\\":\\"a$w6Xby0fHUeCumXfyVQ7ym.iCAkq/Fu2q0ICE7iCYcELWkmU4EY.OW\\",\\"expiry\\":1597772638}}\""], ["updated_at", "2020-08-04 17:43:58.798374"], ["id", 3]]
   (0.4ms)  COMMIT
   (0.1ms)  BEGIN
  User Update (0.2ms)  UPDATE "users" SET "updated_at" = , "sign_in_count" = , "current_sign_in_at" = , "last_sign_in_at" = , "current_sign_in_ip" = , "last_sign_in_ip" =  WHERE "users"."id" =   [["updated_at", "2020-08-04 17:43:58.806598"], ["sign_in_count", 1], ["current_sign_in_at", "2020-08-04 17:43:58.806377"], ["last_sign_in_at", "2020-08-04 17:43:58.806377"], ["current_sign_in_ip", "::1/128"], ["last_sign_in_ip", "::1/128"], ["id", 3]]
   (0.3ms)  COMMIT
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" =  LIMIT   [["id", 3], ["LIMIT", 1]]
Completed 200 OK in 266ms (Views: 0.1ms | ActiveRecord: 2.0ms | Allocations: 11745)

关于同一问题的其他帖子 this 没有帮助

迁移:

lass DeviseTokenAuthCreateUsers < ActiveRecord::Migration[6.0]
  def change
    
    create_table(:users) do |t|
      ## Required
      t.string :provider, :null => false, :default => "email"
      t.string :uid, :null => false, :default => ""

      ## Database authenticatable
      t.string :encrypted_password, :null => false, :default => ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at
      t.boolean  :allow_password_change, :default => false

      ## Rememberable
      t.datetime :remember_created_at

      ## Confirmable
      t.string   :confirmation_token
      t.datetime :confirmed_at
      t.datetime :confirmation_sent_at
      t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at

      ## User Info
      t.string :name
      t.string :nickname
      t.string :image
      t.string :email

      ## Tokens
      t.json :tokens

      t.timestamps
    end

    add_index :users, :email,                unique: true
    add_index :users, [:uid, :provider],     unique: true
    add_index :users, :reset_password_token, unique: true
    add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,       unique: true
  end
end

class AddTrackableToDevise < ActiveRecord::Migration[6.0]

  def up
    add_column :users, :sign_in_count, :integer, default: 0, null: false
    add_column :users, :current_sign_in_at, :datetime
    add_column :users, :last_sign_in_at, :datetime
    add_column :users, :current_sign_in_ip, :inet
    add_column :users, :last_sign_in_ip, :inet
  end

  def down
    remove_columns :users, :sign_in_count, :current_sign_in_at, :last_sign_in_at, :current_sign_in_ip, :last_sign_in_ip
  end
end

user.rb

class User < ActiveRecord::Base
  extend Devise::Models

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  include DeviseTokenAuth::Concerns::User
end

routes.rb

Rails.application.routes.draw do
  mount_devise_token_auth_for 'User', at: 'auth'
end

Gemfile

...
gem 'devise_token_auth'
gem 'rack-cors'
...

application.rb

require_relative 'boot'

require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "active_storage/engine"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_mailbox/engine"
require "action_text/engine"
require "action_view/railtie"
require "action_cable/engine"
# require "sprockets/railtie"
# require "rails/test_unit/railtie"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module TokenAuth3
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.

    # Only loads a smaller set of middleware suitable for API only apps.
    # Middleware like session, flash, cookies can be added back manually.
    # Skip views, helpers and assets when generating a new resource.
    config.api_only = true
  end
end

Rails.application.configure do
  config.middleware.use Rack::Cors do
    allow do
      origins '*'
      resource '*',
               headers: :any,
               expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'],
               methods: [:get, :post, :options, :delete, :put, :patch]
    end
  end
end

我在 Rails 6.0.3.2ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x86_64-darwin19] 上使用仅 API 的应用程序。

我觉得我可能漏掉了一些愚蠢的东西。

我的愚蠢错误。

我只需要将 curl -XGET 更改为 curl -v -XGET 即可显示包含标记的 headers。