Rails:使用 RestClient 的外部 API 集成(400 错误请求)

Rails: External API Integration using RestClient (400 Bad Request)

我正在建设一个数字图书馆,我已经完成了很多需要的功能。我目前在将数字图书馆与 Learning Management System (LMS) 集成时遇到问题。

我已经使用 Devise gem 为数字图书馆创建了管理员身份验证系统。我的目标是允许想要访问数字图书馆的用户使用他们的 Learning Management System (LMS) 凭据(用户名和密码)登录数字图书馆。

我已经获得 Learning Management 系统 (LMS) 的登录 API 端点和其他所需参数,并且我有创建了用户模型会话控制器会话视图模板.

我目前正在使用 RestClient Gem 进行 API 调用,但出现错误 400 Bad Request。我试图调试这个问题,它让我指向 Sessions Controller

中的这一行
 response = RestClient::Request.execute(

下面是我的源代码

会话控制器

require 'rest-client'

class SessionsController < ApplicationController
  def new
  end

  def create
    response = RestClient::Request.execute(
      method: :post,
      url: 'https://newapi.example.com/token',
      payload: { 'username': 'params[:username]',
                 'password': 'params[:password]',
                 'grant_type':'password' },
      headers: { apiCode: '93de0db8-333b-4f478-aa92-2b43cdb7aa9f' }
    )

    case response.code
    when 400
      flash.now[:alert] = 'Email or password is invalid'
      render 'new'
    when 200
      session[:user_id] = user.id
      redirect_to root_url, notice: 'Logged in!'
    else
      raise "Invalid response #{response.to_str} received."
    end
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url, notice: 'Logged out!'
  end
end

会话新视图

<p id=”alert”><%= alert %></p>
<h1>Login</h1>
<%= form_tag sessions_path do %>
  <div class="field">
    <%= label_tag :username %>
    <%= text_field_tag :username %>
  </div>
  <div class="field">
    <%= label_tag :password %>
    <%= password_field_tag :password %>
  </div>
  <div class="actions">
    <%= submit_tag 'Login' %>
  </div>
<% end %>

用户模型

class User < ApplicationRecord
  has_secure_password

  validates :username, presence: true, uniqueness: true
end

我们将不胜感激任何形式的代码示例帮助。如果需要,我也愿意提供有关此集成的更多信息。提前谢谢你。

您应该删除参数周围的引号:

 response = RestClient::Request.execute(
      method: :post,
      url: 'https://newapi.example.com/token',
      payload: { 'username': params[:username],
                 'password': params[:password],
                 'grant_type':'password' },
      headers: { apiCode: '93de0db8-333b-4f478-aa92-2b43cdb7aa9f' }
    )

如果你有引号,这意味着你的 username 值和 password 值是硬编码的..在这里你想从你的中检索 usernamepassword参数。