Skip to content

Unexpected HTTP 401 Errors

Ilyas Garaev edited this page Mar 14, 2017 · 2 revisions

Most common causes

Misplaced Devise callbacks

Simple Token Authentication ensures integration with other Devise authentication strategies through its fallback option. That option takes care of ensuring that Devise authorization mechanisms do not prevent token authentication to be performed.

Unexpected HTTP 401 errors may happen ({"error":"You need to sign in or sign up before continuing."}), when an authenticate_user! callback is placed before the token authentication handler declaration:

In the same controller

Wrong
# app/controllers/some_controller.rb

class SomeController < ApplicationController

  before_action :authenticate_admin! # will prevent token authentication if it fails
  acts_as_token_authentication_handler_for Admin

  # ...
end
Solution
# app/controllers/some_controller.rb

class SomeController < ApplicationController

  acts_as_token_authentication_handler_for Admin

  # Because it defaults to `fallback: :devise`,
  # the token auth. declaration is equivalent to:
  # acts_as_token_authentication_handler_for Admin
  # before_action :authenticate_admin!

  # ...
end

In a parent controller

Wrong
# app/controllers/parent_controller.rb

class SomeController < ParentController

  before_action :authenticate_admin! # will prevent token authentication if it fails

  # I assume that we don't want to remove this callback because
  # it is used by other controllers as well.

  # ...
end
# app/controllers/some_controller.rb

class SomeController < ParentController

  acts_as_token_authentication_handler_for Admin

  # ...
end
Solution
# app/controllers/some_controller.rb

class SomeController < ApplicationController

  # Order matters when defining or skipping callbacks,
  # the Devise callback must be skipped BEFORE declaring token auth. handling
  skip_before_action :authenticate_admin!
  acts_as_token_authentication_handler_for Admin

  # Because it defaults to `fallback: :devise`,
  # the token auth. declaration is equivalent to:
  # acts_as_token_authentication_handler_for Admin
  # before_action :authenticate_admin!

  # ...
end