Ruby实现OAuth2 Token API请求报错,求正确实现方案
问题:将curl POST请求转为Ruby代码时遇到OAuth参数错误
原始curl请求
curl --request POST \ --url '{BASE_URL}/oauth2/token' \ --header 'Authorization: Basic {BASIC_CLIENT}' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials
当前错误的Ruby实现
require 'uri' require 'net/http' url = URI("https://api.userede.com.br/redelabs/oauth2/token") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true request = http.post( url, { 'grant_type' => 'client_credentials' }.to_json, { 'Authorization' => "Basic #{CLIENTID}", 'Content-Type' => 'application/x-www-form-urlencoded'} )
收到的错误响应
{"error_description":"OAuth 2.0 Parameter: grant_type","error":"invalid_request","error_uri":"https://datatracker.ietf.org/doc/html/rfc6749#section-5.2"}
正确的Ruby实现
问题核心是你把请求体转成了JSON格式,但API要求的是application/x-www-form-urlencoded类型的表单数据,JSON格式的内容无法被API正确解析,导致grant_type参数识别失败。
以下是修正后的代码:
require 'uri' require 'net/http' url = URI("https://api.userede.com.br/redelabs/oauth2/token") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true # 生成符合x-www-form-urlencoded格式的请求体 form_data = URI.encode_www_form(grant_type: 'client_credentials') request = Net::HTTP::Post.new(url) request['Authorization'] = "Basic #{CLIENTID}" request['Content-Type'] = 'application/x-www-form-urlencoded' request.body = form_data # 发送请求并获取响应 response = http.request(request) puts response.read_body
关键修正说明
- 移除了
.to_json转换,改用URI.encode_www_form方法生成标准的表单编码字符串,这和curl中--data参数的行为一致 - 显式创建
Net::HTTP::Post对象,更清晰地管理请求头和请求体,避免参数传递混淆
内容的提问来源于stack exchange,提问作者Diogo Amaral
相关产品推荐
相关产品推荐

