Ruby on Rails HTTP Basic authentication with JSON failure message

A short snippet on how to make Ruby on Rails authenticate_or_request_with_http_basic respond with a JSON valid message upon failure.

class ApplicationController < ActionController::API
  include(
    ActionController::HttpAuthentication::Basic::ControllerMethods
  )

  before_action :http_authenticate!

  def http_authenticate!
    authenticate_or_request_with_http_basic do |key, secret|
      return if Resource.find_by(
        key: key,
        secret: secret
      )
    end

    render(
      json: 'Invalid credentials'.to_json,
      status: 401
    )
  end
end

Cover photo by Vladimer Shioshvili on Attribution-ShareAlike 2.0 Generic (CC BY-SA 2.0) license.

The post Ruby on Rails HTTP Basic authentication with JSON failure message appeared first on Running with Ruby.

Ubuntu Server Admin

Recent Posts

AMI and Canonical announce partnership

The collaboration makes it easy to boot directly into Ubuntu from AMI’s UEFI firmware solutions…

1 week ago

The $8.8 trillion advantage: how open source software reduces IT costs

Open source software is known for its ability to lower IT costs. But in 2025,…

1 week ago

Open design: the opportunity design students didn’t know they were missing

What if you could work on real-world projects, shape cutting-edge technology, collaborate with developers across…

1 week ago

Anbox Cloud 1.28.0 is now available!

Enhanced Android device simulation, smarter diagnostics, and OIDC-enforced authentication The Anbox Cloud team has been…

1 week ago