【问题标题】:devise authentication via ruby script通过 ruby​​ 脚本设计身份验证
【发布时间】:2011-08-01 14:32:04
【问题描述】:

我有一个小型应用程序,我将有一些外部应用程序通过 http 将数据发送到此服务并休息。我已经让它工作但没有身份验证。在门户中我使用设计,我的问题是:如何(所需示例)从 ruby​​ 脚本级别对门户进行身份验证?首先要在以下脚本中添加什么来进行身份验证?我想用设计保护这个控制器,然后我需要对以下脚本进行身份验证。

require "net/http"
require "json"

@host = "localhost"
@port = 3000
@post_ws = "/external/rd"

@req_body = {
"device" => {
  "name" => "device_json", 
  "operating_system_id" => "7", 
  "hash_string" => "jfsg3k4ovj0j02jv", 
  "user_id" => "1"
}
}.to_json

req = Net::HTTP::Post.new(@post_ws, initheader = {'Content-Type' =>'application/json'})
req.body = @req_body
response = Net::HTTP.new(@host, @port).start {|http| http.request(req) }

问候, 马特乌斯

【问题讨论】:

  • 我看到 token_authenticable 可能会有所帮助,但目前还不知道如何从脚本中获取令牌,所以仍然没有解决方案:/

标签: ruby ruby-on-rails-3 authentication rest devise


【解决方案1】:

这里是解决方案:

我使用了设计中的 token_authenticable。

Here 是如何用 json 实现它的一个很好的答案。我遇到了一些麻烦并描述了他们in this question。也有答案。

示例代码如下:

require "net/http"
require "json"

@host = "localhost"
@port = 3000
@post_sign = "/users/sign_in.json"
@post_ws = "/external/rd"

@req_sign = {
"user" => {
  "email" => "some@email.com", 
  "password" => "123456" 
}
}.to_json

sig = Net::HTTP::Post.new(@post_sign, initheader = {'Content-Type' => 'application/json'})
sig.body = @req_sign


http = Net::HTTP.new(@host, @port).start
resp1 = http.request(sig)
puts "Response: #{resp1.code} , Message: #{resp1.message} , Body: #{resp1.body}"

if resp1.code == "200" then 
  puts "logged in"
  json_resp = JSON.parse(resp1.body)
  @auth_token = json_resp['auth_token']

  @req_body = {
  "device" => {
    "name" => "device_json", 
    "operating_system_id" => "7", 
    "hash_string" => "jfsg3k4ovj0j02jv" 
  }, 
  "auth_token" => @auth_token 
  }.to_json
  req = Net::HTTP::Post.new(@post_ws, initheader = {'Content-Type' =>'application/json'})
  req.body = @req_body

  response = http.request(req)
  puts "Response: #{response.code} , Message: #{response.message} , Body: #{response.body}"
end

问候, 马特乌斯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 2014-09-03
    • 2018-11-08
    • 1970-01-01
    • 2017-09-18
    • 2012-10-21
    • 2013-10-10
    相关资源
    最近更新 更多