繁体   English   中英

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

[英]Rails basic authentication with cutomized JSON failure message

我在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'}

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

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

如下所示,从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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM