我目前正在将Devise与我的Rails API应用一起使用,以通过devise-jwt对用户进行身份验证。
这是我的用户模型的样子:
class User < ApplicationRecord
devise :database_authenticatable,
:registerable,
:jwt_authenticatable,
jwt_revocation_strategy: JWTBlackList
end
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
这是会话控制器:
class SessionsController < Devise::SessionsController
private
def respond_with(resource, _opts = {})
render json: resource
end
def response_to_on_destroy
head :no_content
end
end
和注册控制器:
class RegistrationsController < Devise::RegistrationsController
respond_to :json
def create
build_resource(sign_up_params)
resource.save
render_resource(resource)
end
end
我运行了下面显示的一些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
但是当我对邮递员/login
运行以下POST请求时,会收到以下消息:
在右侧,您可以看到Rails控制台和服务器,显示凭据正确,但是仍然获得401
关于什么地方可能出问题的任何线索?使用Rails API很难在Devise上找到好的资源。
提前谢谢
答案 0 :(得分:3)
在深入研究SessionsController之后,我发现了它返回401的原因:
warden
试图验证一个空尸体。通过将Content-Type
添加到请求标头中来解决此问题