In my Grape API I've got an endpoint which is responsible of receiving data from CMS webhook - it works well but below specs are failed:
describe ::Webhooks::Cms::ReceiveWebhook, type: :request do
subject(:call) { post endpoint, params: params, headers: basic_authorized_headers(auth_params) }
let(:endpoint) { 'webhooks/Cms' }
let(:params) { { some: 'params' } }
let(:auth_params) do
{
username: Rails.application.credentials.cms_user,
password: Rails.application.credentials.cms_password,
}
end
it 'returns a successful response' do
call
expect(response).to be_successful
end
end
helper with basic_authorized_headers method from headers:
module AuthRequestHelpers
def basic_authorized_headers(username: nil, password: nil)
"#{username}:#{password}"
end
end
I'm getting error:
Failure/Error: subject(:call) { post endpoint, params: params, headers: basic_authorized_headers(auth_params) }
NoMethodError:
undefined method `each' for "test#test.com:password":String
Here is my controller:
module Cms
class ReceiveWebhook < Base
desc 'Receive data of CRUD actions from CMS webhook'
http_basic do |user, password|
user == Rails.application.credentials.cms_user &&
password == Rails.application.credentials.cms_password
end
post :cms do
status 200
end
end
end
post expects a hash for the headers param, you're passing a string.
subject(:call) { post endpoint, params: params, headers: { 'Authorization' => basic_authorized_headers(auth_params) } }
Also, usually basic auth requires the "Basic" keyword, and that the credentials be encoded in Base64:
module AuthRequestHelpers
def basic_authorized_headers(username: nil, password: nil)
encoded_credentials = Base64.encode64("#{username}:#{password}")
"Basic #{encoded_credentials}"
end
end
Related
In my Rails/Grape app I created a webhook controller which receive JSON from CMS webhook. I'm just wondering how to test it in RSpec if I don't have any params (I guess I don't need it because I only receive JSON from webhook).
My webhook controller (it works well):
module Cms
class Webhook < Base
desc 'Take the CMS webhook'
http_basic do |user, password|
user == ENV['USER'] && password == ENV['PASSWORD']
end
post :receive do
params
end
end
end
I was trying to like:
describe Cms::Webhooks, type: :request do
subject(:call) { post endpoint, params: params, as: :json }
let(:endpoint) { '/api/cms/webhooks/receive' }
let(:params) do
{
some: 'some pass'
}
end
it 'returns a successful response' do
call
expect(response).to be_successful
end
end
I'm getting an error:
Failure/Error: expect(response).to be_successful
expected `#<ActionDispatch::TestResponse:0x00007f9058e43e60 #mon_data=#<Monitor:0x00007f9058e43de8>, #mon_data_..., #method=nil, #request_method=nil, #remote_ip=nil, #original_fullpath=nil, #fullpath=nil, #ip=nil>>.successful?` to return true, got false
Can you try this code?
describe Cms::Webhooks, type: :request do
subject(:call) { post endpoint, params: params, as: :son, headers: headers }
let(:endpoint) { '/api/cms/webhooks/receive' }
let(:params) do
{
some: 'some pass'
}
end
let(:headers) do
{
'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials('your_username', 'your_password')
}
end
it 'returns a successful response' do
call
expect(response).to be_successful
end
end
Ref https://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic.html
I'm trying to test CredentialsController, which works fine in production, using RSpec request specs.
Code
Controller
class CredentialsController < ApplicationController
before_action :doorkeeper_authorize!
def me
render json: current_user
end
end
(GET /me routes to CredentialsController#me.)
Request Specs
describe 'Credentials', type: :request do
context 'unauthorized' do
it "should 401" do
get '/me'
expect(response).to have_http_status(:unauthorized)
end
end
context 'authorized' do
let!(:application) { FactoryBot.create(:application) }
let!(:user) { FactoryBot.create(:user) }
let!(:token) { FactoryBot.create(:access_token, application: application, resource_owner_id: user.id) }
it 'succeeds' do
get '/me', params: {}, headers: {access_token: token.token}
expect(response).to be_successful
end
end
end
The unauthorized test passes, but the authorized test fails:
expected #<ActionDispatch::TestResponse:0x00007fd339411248 #mon_mutex=#<Thread::Mutex:0x00007fd339410438>, #mo..., #method=nil, #request_method=nil, #remote_ip=nil, #original_fullpath=nil, #fullpath=nil, #ip=nil>>.successful? to return true, got false
The headers indicate a problem with the token:
0> response.headers['WWW-Authenticate']
=> "Bearer realm=\"Doorkeeper\", error=\"invalid_token\", error_description=\"The access token is invalid\""
token looks okay to me, though:
0> token
=> #<Doorkeeper::AccessToken id: 7, resource_owner_id: 8, application_id: 7, token: "mnJh2wJeEEDe0G-ukNIZ6oupKQ7StxJqKPssjZTWeAk", refresh_token: nil, expires_in: 7200, revoked_at: nil, created_at: "2020-03-19 20:17:26", scopes: "public", previous_refresh_token: "">
0> token.acceptable?(Doorkeeper.config.default_scopes)
=> true
Factories
Access Token
FactoryBot.define do
factory :access_token, class: "Doorkeeper::AccessToken" do
application
expires_in { 2.hours }
scopes { "public" }
end
end
Application
FactoryBot.define do
factory :application, class: "Doorkeeper::Application" do
sequence(:name) { |n| "Project #{n}" }
sequence(:redirect_uri) { |n| "https://example#{n}.com" }
end
end
User
FactoryBot.define do
factory :user do
sequence(:email) { |n| "email#{n}#example.com" }
password { "test123" }
password_confirmation { "test123" }
end
end
Questions
Why am I getting invalid_token on this request?
Do my Doorkeeper factories look correct?
I was passing the token wrong. Instead of:
get '/me', params: {}, headers: {access_token: token.token}
I had to use:
get '/me', params: {}, headers: { 'Authorization': 'Bearer ' + token.token}
You can check your Access Token factory's scopes, It should be same as initializer's default_scopes
e.g.
config/initializers/doorkeeper.rb
default_scopes :read
Below, your Access Token factory's scopes should be
factory :access_token, class: "Doorkeeper::AccessToken" do
sequence(:resource_owner_id) { |n| n }
application
expires_in { 2.hours }
scopes { "read" }
end
Additionally, if you encountered response status: 406 while get '/me'....
It means that the requested format (by default HTML) is not supported. Instead of '.json' you can also send Accept="application/json" in the HTTP header.
get '/me', params: {}, headers: {
'Authorization': 'Bearer ' + token.token,
'Accept': 'application/json'}
I resolved my problem with this solution, maybe you can try it.
Sometimes when I run tests I am getting this error:
TypeError: no implicit conversion of nil into String, which is caused by this code:
params = {
.....
}
auth_headers = {
'Authorization': "Basic #{Base64.encode64('XXX:XXX')}"
}
post back_request_url, params: params, headers: auth_headers
back_request_url path is valid, same params. When the authorization fails, I am getting (as it should be) simply 401 - but, when the authorization passes - then this error happens.
This is something in rails - this action doesn't enter into action provided by back_request_url.
What it could be?
My version of rails is 5.1.3
#FIXED
The issue - Authorization parameters (name and password) has been set in the beginning of the test:
test 'failure no id' do
MyGem.auth_name = 'xxx'
MyGem.auth_pass = 'xxx'
params = {
...
....
(no id)
}
post back_request_url, params: params, headers: #auth_headers
assert_response 400
end
And the action:
class BackRequestController < ApplicationController
protect_from_forgery except: [:new]
http_basic_authenticate_with name: MyGem.auth_name, password: MyGem.auth_pass
...
And they wasn't sometimes set and refreshed, when the test has begun.
Solution
Simply :)
class BackRequestControllerTest < ActionDispatch::IntegrationTest
include Engine.routes.url_helpers
setup do
MyGemauth_name = 'xxx'
MyGem.auth_pass = 'xxx'
#auth_headers = {
'Authorization': "Basic #{Base64.encode64(MyGem.auth_name. + ':' + MyGem.auth_pass)}"
}
end
...
...
...
(TESTS)
I am using devise_auth_token to authenticate users for an API. I would like to authenticate users before each test is run, but keep getting a 401 error. When I use postman to the endpoint with the correct headers, it works, but fails to work during tests.
before(:each) do
#user = FactoryGirl.create(:user)
end
def get_auth
headers = #user.create_new_auth_token
auth = Hash.new
auth["client"] = headers["client"]
auth["access-token"] = headers["access-token"]
auth["uid"] = headers["uid"]
auth["expiry"] = headers["expiry"]
return auth
end
it "auth user should return success" do
get 'get_tasks_for_user', params: {uid: #user.uid}, headers: get_auth
expect(response).to have_http_status(200)
end
RSpec
TasksController auth user should return success
Failure/Error: expect(response).to have_http_status 200
expected the response to have status code 200 but it was 401
You can use a helper method
#/spec/support/helpers/session_helper.rb
module SessionHelper
def set_request_headers(resp)
{ 'ACCEPT' => "application/json",
'Content-Type' => "application/json",
'access-token' => resp['access-token'],
'token-type' => resp['token-type'],
'client' => resp['client'],
'expiry' => resp['expiry'],
'uid' => resp['uid']
}
end
def subdomain_login(uid, password, subdomain)
request_params = {
'email' => uid,
'password' => password
}
host! "#{subdomain}.lvh.me"
post "/portal/auth/sign_in", params: request_params
return set_request_headers(response.headers)
end
end
Make sure you have the following entry in your /spec/rails_helper
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
RSpec.configure do |config|
config.include SessionHelper, :type => :request
end
You can use subdomain_login in your tests. Here is an Rspec example.
post '/portal/system/locations', params: request_params.to_json,
headers: subdomain_login(user_id, password, subdomain)
I have two RSpec tests, a controller spec and a request spec, where I am making a GET request to the index action of the same controller. In both specs I am sending an Authorization header that contains an Oauth2 bearer token.
The problem I'm having is that depending on the type of spec, the header is stored on a different property of the request object. In the case of the request spec, it is available at request.env["Authorization"] and in the case of the controller spec, it is available at request.session["Authorization"].
Why is "Authorization" stored in different places for different types of specs? Is there somewhere I can find it for both specs?
This bearer_token method is in the parent controller class where I'm grabbing the token from the header:
Works with env in the request specs:
def bearer_token
pattern = /^Bearer /
header = request.env["Authorization"] # <= env
header.gsub(pattern, '') if header && header.match(pattern)
end
Works with session in the controller specs:
def bearer_token
pattern = /^Bearer /
header = request.session["Authorization"] # <= session
header.gsub(pattern, '') if header && header.match(pattern)
end
Here is my request spec:
describe '' do
let(:user) { Fabricate(:user) }
describe 'accessing content with valid token' do
let(:token) { OauthToken.create(user: user) }
let(:auth_headers) { {
'Authorization' => "Bearer #{token.access_token}",
'HTTPS' => 'on'
} }
before { get api_v2_cats_path, {}, auth_headers }
specify { response.status.should == 200 }
end
end
Here is my controller spec
describe Api::V2::CatsController do
let(:user) { Fabricate(:user) }
describe ".index" do
let(:token) { OauthToken.create(user: user) }
let(:auth_headers) { {
'Authorization' => "Bearer #{token.access_token}",
'HTTPS' => 'on'
} }
it "should be valid" do
get :index, { format: :json, page_size: 1 }, auth_headers
#json = JSON.parse(response.body)
#json.should_not be_nil
end
end
end
I assumed that the API would be the same for the get method between a request and controller spec. In the controller spec, the third argument is a hash of sessions variables, not header variables. You can set the headers directly on the #request object like so:
describe Api::V2::CatsController do
let(:user) { Fabricate(:user) }
describe ".index" do
let(:token) { OauthToken.create(user: user) }
let(:auth_headers) { {
'Authorization' => "Bearer #{token.access_token}",
'HTTPS' => 'on'
} }
before do
#request.env.merge!(auth_headers)
end
it "should be valid" do
get :index, { format: :json, page_size: 1 }
#json = JSON.parse(response.body)
#json.should_not be_nil
end
end
end
Then the correct way to get the authorization header is using:
def bearer_token
pattern = /^Bearer /
header = request.env["Authorization"] # <= env
header.gsub(pattern, '') if header && header.match(pattern)
end
I found this.
https://github.com/rails/rails/commit/cf9d6a95e805bdddfa9c6b541631d51b3165bf23#diff-10b31f2069dfc4810229c8d60c3a4cda
in your controller, you can do something like this to get the header value.
def index
header_value = request.authorization
end