【问题标题】:Getting "Authentication failure! invalid_credentials: OAuth2::Error" for custom omniauth strategy获取自定义omniauth策略的“身份验证失败!invalid_credentials:OAuth2::Error”
【发布时间】:2016-09-17 11:33:09
【问题描述】:

目前我正在处理 rails 4 项目,现在我必须链接/连接另一个应用程序(不是 sso,而是用于访问 API)说 example.com。 (注意: example.com 使用 3-legged oauth 安全架构)

经过搜索发现我必须实施omniouth策略。

为此,我参考了this 链接。根据Strategy-Contribution-Guide,我可以完成设置和请求阶段,您可以在此处找到我的示例代码。

require 'multi_json'
require 'omniauth/strategies/oauth2'
require 'uri'

module OmniAuth
  module Strategies
    class MyAppStrategy < OmniAuth::Strategies::OAuth2
      option :name, 'my_app_strategy'

   option :client_options, {
    site: site_url,
    authorize_url: authorize_url,
    request_url: request_url,
    token_url: token_url,
    token_method: :post,
    header: { Accept: accept_header }
  }

  option :headers, { Accept: accept_header }
  option :provider_ignores_state, true

  def consumer
    binding.pry
    ::OAuth::Consumer.new(options.client_id, options.client_secret, options.client_options)
  end

  def request_phase # rubocop:disable MethodLength
    binding.pry
    request_token = consumer.get_request_token({:oauth_callback => callback_url}, options.request_params)
    session["oauth"] ||= {}
    session["oauth"][name.to_s] = {"callback_confirmed" => request_token.callback_confirmed?, "request_token" => request_token.token, "request_secret" => request_token.secret}

    if request_token.callback_confirmed?
      redirect request_token.authorize_url(options[:authorize_params])
    else
      redirect request_token.authorize_url(options[:authorize_params].merge(:oauth_callback => callback_url))
    end

  rescue ::Timeout::Error => e
    fail!(:timeout, e)
  rescue ::Net::HTTPFatalError, ::OpenSSL::SSL::SSLError => e
    fail!(:service_unavailable, e)
  end

  def callback_phase # rubocop:disable MethodLength
    fail(OmniAuth::NoSessionError, "Session Expired") if session["oauth"].nil?

    request_token = ::OAuth::RequestToken.new(consumer, session["oauth"][name.to_s].delete("request_token"), session["oauth"][name.to_s].delete("request_secret"))

    opts = {}
    if session["oauth"][name.to_s]["callback_confirmed"]
      opts[:oauth_verifier] = request["oauth_verifier"]
    else
      opts[:oauth_callback] = 'http://localhost:3000/auth/callback' #callback_url
    end

    @access_token = request_token.get_access_token(opts)
    super
    rescue ::Timeout::Error => e
      fail!(:timeout, e)
    rescue ::Net::HTTPFatalError, ::OpenSSL::SSL::SSLError => e
      fail!(:service_unavailable, e)
    rescue ::OAuth::Unauthorized => e
      fail!(:invalid_credentials, e)
    rescue ::OmniAuth::NoSessionError => e
      fail!(:session_expired, e)
  end

  def custom_build_access_token
    binding.pry
    verifier = request["oauth_verifier"]
    client.auth_code.get_token(verifier, get_token_options(callback_url), deep_symbolize(options.auth_token_params))
  end
  alias_method :build_access_token, :custom_build_access_token

  def raw_info
    binding.pry
    @raw_info ||= access_token.get('users/me').parsed || {}
  end

  private

  def callback_url
    options[:redirect_uri] || (full_host + script_name + callback_path)
  end

  def get_token_options(redirect_uri)
    { :redirect_uri => redirect_uri }.merge(token_params.to_hash(:symbolize_keys => true))
  end
end
end

结束

我能够重定向到 example.com,登录后我也能够返回到我的 callback_phase(你会问你是怎么知道的,所以答案是我在 callback_phase 方法中添加了binding.pry 用于检查流程)。

但是在执行策略后我得到以下错误

错误——omniauth: (my_app_strategy) 身份验证失败! invalid_credentials:OAuth2::Error。

调试后发现super 调用出现此错误(来自callback_phase 方法)。

首先我可能存在一些凭据问题,但我可以使用以下方法获取访问令牌(在 super 调用之前执行)

@access_token = request_token.get_access_token(opts)

还有更多信息,我收到了build_access_token 的错误,这是 oauth2 方法

您可以参考this 链接了解更多信息(只需搜索页面上的 build_access_token)。

编辑 - 1

经过调试发现从request method得到这个问题。 (在提出法拉第请求时)。这是代码sn-p

response = connection.run_request(verb, url, opts[:body], opts[:headers]) do |req|
    yield(req) if block_given?
  end

这是我的法拉第请求

#<struct Faraday::Request method=:post, path="example.com/oauth/access_token", params={}, headers={"User-Agent"=>"Faraday v0.9.2", "Content-Type"=>"application/x-www-form-urlencoded"}, body={"grant_type"=>"authorization_code", "code"=>"aPexxxvUg", "client_id"=>"xxxxxur303GXEch7QK9k", "client_secret"=>"xxxxxxcad97b3d252e2bcdd393a", :redirect_uri=>"http://localhost:3000/auth/my_app_strategy/callback"}, options=#<Faraday::RequestOptions (empty)>>

作为回应,我收到以下错误消息

HTTP 状态 400 - OAuth 消费者凭据不足。

那么任何人都可以帮助解决这个问题吗?

是否有任何其他方式来存储访问令牌,以便我可以将其用于通信目的。 谢谢

【问题讨论】:

  • 您已在此处公开了您的使用者密钥和使用者密码。我试图将它们编辑出来,但是在编辑生效之前需要得到其他人的确认。请确保立即取消这些凭据并获取新的凭据,并保密。
  • @ScottS。谢谢你的回复,我会处理的。顺便说一句,这些是随机数。
  • 您有没有使用github.com/intridea/omniauth-oauth2/blob/master/lib/omniauth/… 来设置您的oauth 的原因?
  • @RaviSankarRaju,是的,实际上我首先厌倦了使用它,但出现“oauth_token”不存在的错误。因此,我为请求阶段手动创建了消费者并使用它。

标签: ruby-on-rails ruby oauth faraday


【解决方案1】:

首先,我想弄清楚 Oauth2 是如何工作的:

Oauth2,协议说:

  1. 您将用户重定向到提供者登录端点,添加一些必需的参数(Ejm:PROVIDER/public/oauth?redirect_uri=MYWEB/oauthDemo& response_type=code&client_id=ABCDE)。有时还有一个范围/权限/资源参数表明你的目的。

    -> 然后用户登录并使用代码重定向到您的端点 MYWEB/public/oauth

  2. 现在您必须通过 POST 请求访问令牌到提供者端点。示例:

    POST PROVIDER?code=d5Q3HC7EGNH36SE3N& client_id=d4HQNPFIXFD255H& client_secret=1a98b7cb92407cbd8961cd8db778de53& 重定向uri=https://example.com/oauthDemo& grant_type=authorization_code

  3. 现在您有了 access_token,您可以使用它来获取信息或使用 JWT 对其进行解码。


清楚这一点,并看到您的通话似乎正确:

  #<struct Faraday::Request method=:post, path="PROVIDER/oauth/access_token", params={}, headers={"User-Agent"=>"Faraday v0.9.2", "Content-Type"=>"application/x-www-form-urlencoded"}, body={"grant_type"=>"authorization_code", "code"=>"aPexxxvUg", "client_id"=>"xxxxxur303GXEch7QK9k", "client_secret"=>"xxxxxxcad97b3d252e2bcdd393a", :redirect_uri=>"MYWEB/auth/my_app_strategy/callback"}, options=#<Faraday::RequestOptions (empty)>>

由于响应是“HTTP 状态 400 - OAuth 消费者凭据不足。”,我想也许你:

一个。您的客户端在 Provider 上的配置不正确。通常你会在提供者网站上进行基本配置,这样他才能认出你。所以可能配置不好。

b.第一步(重定向到提供者)缺少资源/权限/范围参数或配置错误。所以当你要token的时候就有问题了。

【讨论】:

  • 与提供商团队讨论过,他们说他们支持OAuth1 而不是OAuth2,因此在策略文件中进行了更改。它可以找到能够获取详细信息(access_token)的工作。感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 2017-08-27
  • 1970-01-01
  • 2022-08-10
  • 1970-01-01
  • 2021-03-23
相关资源
最近更新 更多