Skip to content

Instantly share code, notes, and snippets.

@zerobearing2
Created April 20, 2012 19:40
Show Gist options
  • Save zerobearing2/2431247 to your computer and use it in GitHub Desktop.
Save zerobearing2/2431247 to your computer and use it in GitHub Desktop.
Rails 3.2.x HTTP Basic 401 as JSON
# Overload rails 3.2.x default HTTP Baisc 401 response
# to JSON instead of plain text/html.
#
# Examples
#
# require 'json_401'
# class ApiController < ActionController::Metal
# ...
# end
#
module ActionController::HttpAuthentication::Basic
def authentication_request(controller, realm)
controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
controller.response.headers["Content-Type"] = "application/json"
controller.response_body = {error: "Access denied."}.to_json
controller.status = 401
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment