Skip to content

Customizing the response body when unauthorized

Yaman ALTareh edited this page Oct 3, 2017 · 7 revisions

By default, doorkeeper returns a simple header-only response of 401:Unauthorized when the token is invalid. The code for this behavior is located here.

For rails, a message can be added to the response body in this case by defining a method in your controller, like so:

class ApplicationController < ActionController::Base
  def doorkeeper_unauthorized_render_options(error: nil)
    { json: { error: "Not authorized" } }
  end
end

if you use oauth/token and you need to customize the error response, adding doorkeeper_unauthorized_render_options in your controller will not work, cause /token action use Doorkeeper::OAuth::ErrorResponse not doorkeeper_unauthorized_render_options, so to override it you have to sth like this:

module Doorkeeper
  module OAuth
    class ErrorResponse
      def body
        {
          error:
            { # // name, description variables come from ErrorResponse instance, you can use them here ...
              key: name,
              message: description
            }
        }
      end
    end
  end
end

For grape, The code for this behavior is located here. a message can be added to the response body in this case by defining a helper method in your grape.

class Base < Grape::API
  helpers do
    def doorkeeper_render_error_with(error)
      status_code = case error.status
                    when :unauthorized
                      401
                    when :forbidden
                      403
                    end

      error!({ error: error.description }, status_code, error.headers)
    end
  end
end
Clone this wiki locally