我目前正在将 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
这是 session Controller :
class SessionsController < Devise::SessionsController
private
def respond_with(resource, _opts = {})
render json: resource
end
def response_to_on_destroy
head :no_content
end
end
和注册 Controller :
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 请求时在 Postman 上,我收到以下消息:在右侧,您可以看到 rails 控制台和服务器,显示凭据是正确的,但我们仍然得到 401
关于可能出什么问题的任何线索?使用 Rails API 很难在 Devise 上找到好的资源。
先感谢您
最佳答案
在深入研究 SessionsController 后,我找到了它返回 401 的原因:warden
试图验证一个空的 body 。通过添加 Content-Type
修复了此问题到请求头
关于ruby-on-rails - Rails Devise API - 登录路由响应 `You need to sign in or sign up before continuing.`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52712134/