Tag: http basic auth

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.

Ruby on Rails: RailsAdmin + HTTP Basic authentication

RailsAdmin is an awesome gem when you want to build a not-so-much custom admin panel. Unfortunately it's not mentioned in documentation (or at least I couldn't find it) how to use it with HTTP Basic authentication. Here is an example of how to do this (put this in your config/initializers/rails_admin.rb file):

RailsAdmin.config do |config|
  config.authenticate_with do
    authenticate_or_request_with_http_basic do |username, password|
      username == 'user' &&
      password == 'password'
    end
  end

  # Other config stuff should go here
end

You should also use gem like SettingsLogic for storing credentials like this:

RailsAdmin.config do |config|
  config.authenticate_with do
    authenticate_or_request_with_http_basic do |username, password|
      username == System::Settings.admin.username &&
      password == System::Settings.admin.password
    end
  end

  # Other config stuff should go here
end

Copyright © 2024 Closer to Code

Theme by Anders NorenUp ↑