Rails基本身份验证和定制化的JSON失败消息

时间:2019-07-05 11:34:55

标签: ruby-on-rails ruby ruby-on-rails-5 basic-authentication

我有一个处于API模式的Rails 5.2应用程序。如果为请求提供了正确的基本身份验证凭据,则将呈现预期的JSON数据{ status: true, data: 'test_user_data' }

users_controller.rb

class Api::UsersController < ApplicationController
  before_action :basic_authenticate

  def get_user_info
    render json: { status: true, data: 'test_user_data' }
  end

  private

  def basic_authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username == 'test_name' && password == 'test_password'
    end
  end
end

application_controller.rb

class ApplicationController < ActionController::API
    include ActionController::HttpAuthentication::Basic::ControllerMethods
end

但是,如果基本身份验证失败,则仅呈现纯文本HTTP Basic: Access denied.

我想做的是在验证失败的情况下以JSON格式显示错误消息,例如{ status: false, message: 'basic authentication failed'}

解决该问题的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

authenticate_or_request_with_http_basic采用可选的message参数(不幸的是,它是参数列表中的第二个参数,因此第一个参数为"Application")。

在Rails 5中,只需将代码更改为:

def basic_authenticate
  message = { status: false, message: 'basic authentication failed' }.to_json

  authenticate_or_request_with_http_basic("Application", message) do |username, password|
    username == 'test_name' && password == 'test_password'
  end
end

Rails 6中的实现已更改,因此在Rails 6中,最基本的实现如下所示:

def basic_authenticate
  message = { status: false, message: 'basic authentication failed' }.to_json

  authenticate_or_request_with_http_basic(nil, message) do |username, password|
    username == 'test_name' && password == 'test_password'
  end
end

答案 1 :(得分:0)

像下面一样从application_controller.rb中进行救援

rescue_from User::NotAuthorized, with: :deny_access # self defined exception

def deny_access
  render json: { status: false, message: 'basic authentication failed'}
end