我有一个仅限 Rails 5 API 的应用程序,并使用 Knock 进行 JWT 身份验证。
完成模型和模型规范后,我开始做请求规范。
但我不知道如何以正确的方式完成请求规范内的身份验证,
我的用户 Controller ,
module V1
class UsersController < ApplicationController
before_action :authenticate_user, except: [:create]
end
end
应用程序 Controller ,
class ApplicationController < ActionController::API
include Knock::Authenticable
include ActionController::Serialization
end
我最愚蠢的解决方案(在其余请求之前调用获取 token 请求以获取 JWT),
context 'when the request contains an authentication header' do
it 'should return the user info' do
user = create(:user)
post '/user_token', params: {"auth": {"email": user.email, "password": user.password }}
body = response.body
puts body # {"jwt":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0ODgxMDgxMDYsInN1YiI6MX0.GDBHPzbivclJfwSTswXhDkV0TCFCybJFDrjBnLIfN3Q"}
# use the retrieved JWT for future requests
end
end
如有任何建议,我们将不胜感激。
最佳答案
def authenticated_header(user)
token = Knock::AuthToken.new(payload: { sub: user.id }).token
{ 'Authorization': "Bearer #{token}" }
end
describe 'GET /users?me=true' do
URL = '/v1/users?me=true'
AUTH_URL = '/user_token'
context 'when the request with NO authentication header' do
it 'should return unauth for retrieve current user info before login' do
get URL
expect(response).to have_http_status(:unauthorized)
end
end
context 'when the request contains an authentication header' do
it 'should return the user info' do
user = create(:user)
get URL, headers: authenticated_header(user)
puts response.body
end
end
end
关于ruby-on-rails - 如何使用 RSpec 为 JWT 验证应用程序制定请求规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42326434/