Authentication

Token based authencitation

in controllers tests, setting header "Authorization" as following

let(:data){ "some data" }
subject do
  request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Token.encode_credentials("token")
  post :create, data
 end

in Cucumber steps

When(/^the client requests POST "(.*?)" with details as following:$/) do |path, table|
  reservation_info = table.rows_hash
  post path,
  {
    reservation:{
      title: reservation_info["Title"],
      first_name: reservation_info["First name"],
      last_name: reservation_info["Last name"],
      phone_number: reservation_info["Phone number"],
      guest: reservation_info["Guest"],
      email: reservation_info["Email"],
      reserved_time: reservation_info["Reserved time"],
      special_request: reservation_info["Special request"]}
  },
    { 'HTTP_AUTHORIZATION' => Macros.token_encode(@user_token) }
end

in integration tests

subject do
  post :create, data,  { 'Authorization' => ActionController::HttpAuthentication::Token.encode_credentials("token") }
 end

Liminations

authenticate_or_request_with_http_token: halt the request and render in html format with "access denied" message, so if your authenciate method is something like:

def authenticate
 authenticate_token || render_unauthorized
end

def authenticate_token
  authenticate_or_request_with_http_token do |token, options|
    User.find_by(auth_token: token)
  end
end

The method render_unauthorized will never be called due to authenticate_or_request_with_http_token has taken over the unauthorized request handeling.

Instead, using authenticate_with_http_token, does not halt the request and just return a boolean, so render_unauthorized will be invoked when the returns of authenticate_with_http_token is false.

def authenticate_token
  authenticate_with_http_token do |token, options|
    User.find_by(auth_token: token)
  end
end

Reference

results matching ""

    No results matching ""