从Rails登录外部站点

时间:2016-08-26 13:10:25

标签: ruby-on-rails external sign

我想通过基于保存到rails数据库的用户/密码凭据的rails登录到外部https站点。像单点登录的东西。外部站点不提供登录API;只有一个登录表单。他们的文档说,您可以通过将电子邮件和密码加载到表单然后按确定将凭据发布到他们的登录表单。

但是如果我这样做,那么通过查看登录表单的源代码,有人可能会找到登录凭据。我查看了Mechanize并加载了像Submitting POST data from the controller in rails to another websiteRails 3 - Log into another site and keep cookie in session这样的Cookie,但这似乎不对。

有没有办法从控制器自动加载凭据并立即发布到外部网站以登录该网站?

提前谢谢

2 个答案:

答案 0 :(得分:2)

我会使用Oauth2。这是一个很好的包装器:https://github.com/intridea/oauth2

答案 1 :(得分:0)

我能够通过机械化来做到这一点。例如,对于使用https的facebook,代码如下所示

在我的 user_controller.rb

  def face_book
    @website = 'https://www.facebook.com/login.php?login_attempt=1&lwv=110' 
    agent = Mechanize.new
    agent.log = Logger.new "mechanize.log"
    agent.user_agent_alias = 'Mac Safari'
    agent.follow_meta_refresh = true
    agent.redirect_ok = true
    login_page  = agent.get (@website)
    login_form = login_page.forms.first 
    email_field = login_form.field_with(name: "email")
    password_field = login_form.field_with(name: "pass")  
    email_field.value = 'PUT_YOUR_EMAIL_HERE'
    password_field.value = 'PUT_YOUR_PASSWORD_HERE'
    home_page = login_form.click_button
    @blah = agent.get("https://m.facebook.com/")
  end