2011-08-01 35 views
1

我有一个小应用程序,并且我将有一些外部应用程序通过http将剩余的数据放到这个服务上。我已经有它的工作,但没有身份验证。在门户网站我使用设计,我的问题是:如何(例如所需)从红宝石脚本级别验证门户?要添加到以下脚本中以便首先进行身份验证?我想用devise保护这个控制器,然后我需要认证部分以下脚本。通过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) } 

问候, Mateusz

+0

我看到token_authenticatable可能有帮助,但至今不知道,如何从脚本的道理,所以仍然没有解决:/ – Mateusz

回答

4

这里是溶液:

我用从色器件token_authenticatable。

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

这里去示例代码:

require "net/http" 
require "json" 

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

@req_sign = { 
"user" => { 
    "email" => "[email protected]", 
    "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 

问候, Mateusz