Rails Devise API - 登录路由响应`您需要在继续之前登录或注册

Joh*_*Cdf 6 rspec ruby-on-rails devise rails-api

我目前正在使用Devise和我的Rails API应用程序来使用devise-jwt对用户进行身份验证.

这是我的用户模型的样子:

class User < ApplicationRecord
  devise :database_authenticatable,
         :registerable,
         :jwt_authenticatable,
         jwt_revocation_strategy: JWTBlackList
end
Run Code Online (Sandbox Code Playgroud)

config/routes.rb设置如下:

Rails.application.routes.draw do
  devise_for :users,
         path: '',
         path_names: {
           sign_in: 'login',
           sign_out: 'logout',
           registration: 'signup'
         },
         controllers: {
           sessions: 'sessions',
           registrations: 'registrations'
         }
end
Run Code Online (Sandbox Code Playgroud)

这是会话控制器:

class SessionsController < Devise::SessionsController

  private

  def respond_with(resource, _opts = {})
    render json: resource
  end

  def response_to_on_destroy
    head :no_content
  end
end
Run Code Online (Sandbox Code Playgroud)

和注册控制人:

class RegistrationsController < Devise::RegistrationsController
  respond_to :json

  def create
    build_resource(sign_up_params)

    resource.save
    render_resource(resource)
  end
end
Run Code Online (Sandbox Code Playgroud)

我运行了一些Rspec测试,如下所示,这些测试都是成功的

require 'rails_helper'

RSpec.describe SessionsController, type: :request do
  let(:user) { create(:user) }
  let(:url) { '/login' }
  let(:params) do
    {
      user: {
        email: user.email,
        password: user.password
      }
    }
  end

  context 'when params are correct' do
    before do
      post url, params: params
    end

    it 'returns 200' do
      expect(response).to have_http_status(200)
    end

    it 'returns JTW token in authorization header' do
      expect(response.headers['Authorization']).to be_present
    end

    it 'returns valid JWT token' do
      decoded_token = decoded_jwt_token_from_response(response)
      expect(decoded_token.first['sub']).to be_present
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

但是当我/login在Postman上运行以下POST请求时,我得到以下消息:

邮差要求

在右侧,您可以看到rails控制台和服务器,显示凭据是正确的,但我们仍然得到401

什么可能是错的线索?使用Rails API在Devise上很难找到好的资源.

先感谢您

Joh*_*Cdf 4

在深入研究 SessionsController 之后,我发现它返回 401 的原因: warden正在尝试验证一个空主体。通过添加Content-Type到请求标头修复了此问题