【问题标题】:Rails custom consumer oauth strategyRails 自定义消费者 oauth 策略
【发布时间】:2014-02-05 11:16:24
【问题描述】:

我是 oauth 和 api 集成的新手,并且有一段时间(我可以在这里说)试图弄清楚它。

我想将我的 rails 应用程序连接到 Magento(一个 php 电子商务购物车)。

他们在这里有一些基本的文档:

http://www.magentocommerce.com/api/rest/authentication/oauth_authentication.html

虽然我原则上理解 oauth 的概念,但我不知道如何实现自定义解决方案。我使用了一些 gem(例如:omniauth)连接到 Twitter,这很好,但我只是不知道如何创建自己的连接到 Magento 的策略。

有人知道怎么做吗?有没有我可以使用的演练或截屏视频?

如果不是,您会建议我使用哪些工具或方法来解决这个问题——如果只是通过反复试验?

提前感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails magento oauth


    【解决方案1】:

    以下是我创建的 omniauth-magento gem / strategy 的 repo 的详细说明:

    设置 Magento

    消费者密钥和秘密

    在 Magento 中设置一个消费者并记下消费者密钥和消费者秘密

    特权

    在 Magento Admin 后台,进入 System > Web Services > REST Roles,选择 Customer,然后在 下勾选 Retrieve客户。根据需要添加更多权限。

    属性

    在 Magento Admin 后台,进入 System > Web Services > REST Attributes,选择 Customer,然后勾选 Email, 客户>阅读下的名字姓氏。根据需要添加更多属性。

    设置 Rails

    这些说明的一部分基于这些OmniAuth instructions,您可以阅读以防遇到困难。

    设计

    如果您还没有安装Devise,请安装它

    在您的 routes.rb 中添加/替换这一行。一旦 Magento 成功授权并返回 Rails 应用程序,就会调用它。

    devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks"}
    

    Magento oAuth 策略

    将此库加载到您的 Gemfile gem "omniauth-magento" 并运行 bundle install

    修改config/initializers/devise.rb

    Devise.setup do |config|
      # deactivate SSL on development environment
      OpenSSL::SSL::VERIFY_PEER ||= OpenSSL::SSL::VERIFY_NONE if Rails.env.development? 
      config.omniauth :magento,
        "ENTER_YOUR_MAGENTO_CONSUMER_KEY",
        "ENTER_YOUR_MAGENTO_CONSUMER_SECRET",
        { :client_options => { :site => "ENTER_YOUR_MAGENTO_URL_WITHOUT_TRAILING_SLASH" } }
      # example:
      # config.omniauth :magento, "12a3", "45e6", { :client_options =>  { :site => "http://localhost/magento" } }
    

    可选:如果您想使用 Admin API(而不是 Customer API),您需要像这样覆盖默认的 authorize_path:

    { :client_options => { :authorize_path => "/admin/oauth_authorize", :site => ENTER_YOUR_MAGENTO_URL_WITHOUT_TRAILING_SLASH } }
    

    在您的文件夹 controllers 中,创建一个子文件夹 users

    在该子文件夹 app/controllers/users/ 中,使用以下代码创建文件 *omniauth_callbacks_controller.rb*:

    class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
      def magento
        # You need to implement the method below in your model (e.g. app/models/user.rb)
        @user = User.find_for_magento_oauth(request.env["omniauth.auth"], current_user)
    
        if @user.persisted?
          sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
          set_flash_message(:notice, :success, :kind => "magento") if is_navigational_format?
        else
          session["devise.magento_data"] = request.env["omniauth.auth"]
          redirect_to new_user_registration_url
        end
      end
    end
    

    用户模型和表格

    这是一个有用的 Magento 信息示例,您可以在创建这些列后将其存储在 User 表中:

    • 电子邮件
    • 名字
    • 姓氏
    • magento_id
    • magento_token
    • magento_secret

    可选:例如,您可能希望使用 *attr_encrypted gem* 加密 *magento_token* 和 *magento_secret*(需要将 magento_token 重命名为 encrypted_magento_token,将 magento_secret 重命名为 encrypted_magento_secret)。

    将您的 User 模型设置为 omniauthable :omniauthable, :omniauth_providers =&gt; [:magento],并创建一个方法以在成功验证后保存检索到的信息。

    class User < ActiveRecord::Base  
      devise :database_authenticatable, :registerable, :recoverable,
             :rememberable, :trackable, :validatable, :timeoutable,
             :omniauthable, :omniauth_providers => [:magento]  
    
      def self.find_for_magento_oauth(auth, signed_in_resource=nil)
        user = User.find_by(email: auth.info.email)
        if !user
          user = User.create!(
            first_name: auth.info.first_name,                           
            last_name:  auth.info.last_name,
            magento_id: auth.uid,
            magento_token: auth.credentials.token,
            magento_secret: auth.credentials.secret,
            email:      auth.info.email,
            password:   Devise.friendly_token[0,20]
          )
        else
          user.update!(
            magento_id: auth.uid,
            magento_token: auth.credentials.token,
            magento_secret: auth.credentials.secret
          )
        end    
        user
      end         
    end
    

    开始认证的链接

    将此行添加到您的视图&lt;%= link_to "Sign in with Magento", user_omniauth_authorize_path(:magento) %&gt;

    身份验证

    启动你的 Rails 服务器

    启动您的 Magento 服务器

    使用客户帐户(或管理员帐户,如果您想使用管理 API)登录 Magento

    在您的 Rails 应用程序中,转到您粘贴此行的视图 &lt;%= link_to "Sign in with Magento", user_omniauth_authorize_path(:magento) %&gt;

    点击链接

    您现在应该被引导到 Magento 视图,提示您授权访问 Magento 用户帐户

    确认后,您应该登录到 Rails 并重定向到上面指定的 Rails 回调 URL。用户现在应该存储了 magento_id、magento_token 和 magento_secret。

    进行 API 调用

    创建一个使用 magento_token 和 magento_secret 进行 API 调用的类,例如在 *lib/magento_inspector.rb* 中。示例:

    class MagentoInspector
      require "oauth"
      require "omniauth"
      require "multi_json"
    
      def initialize
        @access_token = prepare_access_token(current_user) # or pass user in initialize method 
        @response = MultiJson.decode(@access_token.get("/api/rest/customers").body) # or pass query in initialize method, make sure privileges and attributes are enabled for query (see section at top)
      end
    
    private
    
      # from http://behindtechlines.com/2011/08/using-the-tumblr-api-v2-on-rails-with-omniauth/
      def prepare_access_token(user)
        consumer = OAuth::Consumer.new("ENTER_YOUR_MAGENTO_CONSUMER_KEY", "ENTER_YOUR_MAGENTO_CONSUMER_SECRET", {:site => "ENTER_YOUR_MAGENTO_URL_WITHOUT_TRAILING_SLASH"})
        token_hash = {:oauth_token => user.magento_token, :oauth_token_secret => user.magento_secret}
        access_token = OAuth::AccessToken.from_hash(consumer, token_hash)
      end
    end
    

    确保 Rails 将文件加载到放置此类的文件夹中。对于 lib 文件夹,将其放入 config/application.rbconfig.autoload_paths += Dir["#{config.root}/lib/**/"]

    查询MagentoInspector.new

    扩展课程以满足您的需求

    【讨论】:

    • 有没有办法动态设置 Magento 站点?
    • 如果你希望它依赖于环境,你可以使用 ENV 变量。这就是你所追求的吗?
    【解决方案2】:

    当我听到 M 字 (Magento) 时,我得到了这种喉音响应,我花了几个月的时间试图让它做任何有用的事情。但是...假设您别无选择,并且假设 Magento 提供标准的 OAuth 服务器,那么您应该能够使用 OmniAuth 连接到 Mag...blurrgh..ento。

    Magento 需要提供几个令牌,client_id 和 client_secret。您可以使用这些来为您的应用请求访问令牌。拥有它后,您可以半永久性地重复使用它。 OmniAuth 或许可以帮助您。

    获得访问令牌后,您需要在向服务发出的每个请求中传递一个类似于 Authentication: OAuth &lt;access-token&gt; 的 HTTP 标头。

    使用标准 https(我希望,vs http)向服务器发出请求。在 Rails 中,您可以使用自己的 REST 客户端(使用 Net::HTTP 和朋友),但您可能会发现像 RestClient, linked here 这样的 gem。还有其他的——检查The Ruby Toolbox for more

    这能让你开始吗?

    【讨论】:

    • 谷歌“magento 烂透了”,只是一笑而过。
    • 是的,这有帮助。我正在尝试http,但需要https。现在搞定了。谢谢!
    猜你喜欢
    • 2011-08-23
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    相关资源
    最近更新 更多