【发布时间】:2016-10-20 20:05:48
【问题描述】:
负责的代码不是特定于环境的,但它可以在本地工作,但不能在生产环境中工作:
对我的应用程序 /oauth/token 的 POST 请求应重定向到覆盖默认 Doorkeeper 令牌响应的控制器,如第一条路由所示
routes.rb
require 'api_constraints'
Rails.application.routes.draw do
use_doorkeeper do
controllers :tokens => 'access_token'
end
# Other routes
end
以上内容在本地服务器上运行良好,但在生产 [Heroku] 中,这似乎被忽略了,而是无缘无故地路由到默认的门卫类。因此,带有令牌的响应不包含用户 ID。
请求“https://myapp.herokuapp.com/oauth/token”
POST /oauth/token HTTP/1.1
Host: myapp.herokuapp.com
Cache-Control: no-cache
Postman-Token: xxxxxxxx
Content-Type: application/x-www-form-urlencoded
grant_type=password&email=john%40gmail.com&password=password
这会返回 JSON 响应:
{
"access_token": "XXXXXX",
"token_type": "bearer",
"created_at": 1466340696
}
对“http://localhost:3000/oauth/token”的相同请求返回
{
"access_token": "XXXXXX",
"token_type": "bearer",
"created_at": 1466341435,
"id": 1
}
使用正确包含的 user_id。我不确定是否存在某种缓存问题导致我的生产服务器使用旧的路由文件。我尝试重新启动 dynos 并将进一步的更改推送到 heroku master,但这并没有解决问题。
access_token_controller
class AccessTokenController < Doorkeeper::TokensController
# Overriding create action
# POST /oauth/token
def create
response = strategy.authorize
body = response.body
if response.status == :ok
# User the resource_owner_id from token to identify the user
user = User.where(response.token.resource_owner_id).first rescue nil
unless user.nil?
### If you want to render user with template
### create an ActionController to render out the user
# ac = ActionController::Base.new()
# user_json = ac.render_to_string( template: 'api/users/me', locals: { user: user})
# body[:user] = Oj.load(user_json)
### Or if you want to just append user using 'as_json'
body[:id] = response.token.resource_owner_id
end
end
self.headers.merge! response.headers
self.response_body = body.to_json
self.status = response.status
rescue Doorkeeper::Errors::DoorkeeperError => e
handle_token_exception e
end
end
如有任何困惑,我们深表歉意,并提前感谢您对此提供的任何帮助。
【问题讨论】:
-
你确定你的 Heroku 机器上有对应的
User吗? -
嗨@Uzbekjon,是的,我确定。我可以使用用户帐户正常登录,也可以通过 JSON API 检索访问令牌,但是只有 localhost 上的 JSON 响应按应有的方式附加了
id参数,heroku 只发送 3 个其他字段,就像之前的实现一样我的代码。 -
@Uzbekjon 用户出现在机器上,但似乎没有分配到
user = User.where(response.token.resource_owner_id).first rescue nil,谢谢您的帮助
标签: ruby-on-rails heroku oauth doorkeeper