我有一个使用mongoid和Devise进行用户认证的Rails web应用程序。我想添加用于iOS应用程序的API功能,所以我添加了devise_token_auth gem(为了使它适用于mongoid,但它似乎正常工作)。现在我正在寻找一些关于如何使用devise_token_auth添加到用户记录的令牌的帮助。如何在Rails中使用由DeviseTokenAuth设置的令牌
我使用测试Ruby脚本,看起来像这样:
require 'httparty'
base_uri = "http://localhost:3000/api/v1/auth/sign_in"
uri = URI.parse(base_uri)
email = "[email protected]"
password = "abc123"
payload = {email: email, password: password }
response = HTTParty.post(base_uri, :body => payload)
puts "Response: #{response.message}"
puts "Response: #{response.body}"
当我执行这个脚本,一个新的字段添加到与电子邮件的用户数据库记录[email protected] ,所以它看起来像这样:
"_id" : ObjectId("5571db594169727489000000"),
"email" : "[email protected]",
"encrypted_password" : "$2a$10$9cgGVPYuaW2Bb1y",
"name" : "Test User",
"updated_at" : ISODate("2015-10-09T20:34:09.711Z"),
"created_at" : ISODate("2015-06-05T17:24:41.734Z"),
"tokens" : {
"J0eQp5hL8HfYvigrJOUQ" : {
"token" : "$2a$10$xxJ84bQGH93zpMtI0W",
"expiry" : 1445632449
}
},
"uid" : "abcxyz"
一切都很好,很好。响应主体包含除密码字段和令牌字段以外的所有上述用户数据。现在我无法从文档中找出如何将这个新的令牌用于后续的API调用。令牌信息不会在响应主体中返回。
devise_token_auth文档声明:“每个请求所需的验证头将在前一个请求的响应中可用。”以下是我在回复中看到的除用户记录信息之外的内容:
@response=#<Net::HTTPOK 200 OK readbody=true>, @headers={"x-frame-options"=>["SAMEORIGIN"], "x-xss-protection"=>["1; mode=block"], "x-content-type-options"=>["nosniff"], "content-type"=>["application/json; charset=utf-8"], "etag"=>["W/\"2258296e307edb117bc9e81b83fb71a8\""], "cache-control"=>["max-age=0, private, must-revalidate"], "x-request-id"=>["26f956cd-9924-42e0-bbfa-5878a3651339"], "x-runtime"=>["0.424290"], "connection"=>["close"], "transfer-encoding"=>["chunked"]}>
如何使用该信息提出其他请求?
我的控制器代码如下所示:
class Api::V1::ApiCommentsController < ApplicationController
include DeviseTokenAuth::Concerns::SetUserByToken
before_action :authenticate_user!
def index
render json: {
data: {
message: "Welcome, #{current_user.name}!"
}
}, status: 200
end
end
我想用一个类似于我上面列出的脚本来进行测试,沿着这些线路:
require 'httparty'
uid = "123"
base_uri = "http://localhost:3000/comments_api"
uri = URI.parse(base_uri)
payload = {"uid" => uid, "access-token" => "???" }
response = HTTParty.get(base_uri, headers: payload)
puts "Response: #{response.message}"
puts "Response: #{response.body}"
我不知道访问令牌字段中应该发生什么,或者是否需要任何额外的头文件来验证用户。非常感谢您的帮助。