gpt4 book ai didi

ruby-on-rails - 如何以 json 形式返回 Doorkeeper 访问 token

转载 作者:行者123 更新时间:2023-12-01 18:12:00 26 4
gpt4 key购买 nike

我正在尝试为 iOS 应用程序创建一个登录系统,其后端由设备和门卫提供支持。

我想限制网络请求的数量,因此不想从凭据中获取 token ,然后将用户详细信息作为单独的请求获取。

这是我当前的尝试:

token = Doorkeeper::AccessToken.create!(application_id: @application_id,
resource_owner_id: current_user.id, :expires_in => 168.hours)
puts token.token
render :json => {:user => current_user, :token => token.as_json(:include=> token)},
status: :ok, location: :users

但是返回的是:

{"user":{"id":2,"email":"user3@test.com","created_at":"2014-06-12T17:25:12.000Z",
"updated_at":"2014-06-13T12:20:18.536Z",
"firstName":"user","lastName":"test","subscription":null},
"token":{"resource_owner_id":2,"scopes":[],"expires_in_seconds":604800,
"application":{"uid":"[Filtered]"}}}

因此,实际的 access_token key 不会被传回以允许我将来进行调用。我可以看到 token 本身没有在 DoorKeeper::AccessToken.as_json 中返回,但是 token.as_json(:include=> token) 仍然没有返回它.

有谁知道如何以 json 形式返回 AccessToken,包括访问 token 本身?

最佳答案

我处理这个问题的方法是创建一个自定义 token Controller 并覆盖 token 请求操作。在那里我可以将自定义内容附加到响应中。

# app/controllers/custom_tokens_controller.rb
class CustomTokensController < 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.find(response.token.resource_owner_id) 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[:user] = user.as_json
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

只需确保您在routes.rb中指向此 Controller

# routes.rb
Rails.application.routes.draw do

# Doorkeeper
use_doorkeeper do
controllers :tokens => 'custom_tokens'
end

# Your other routes here...

end

这已经过测试并且有效,我正在我的项目中使用它。

关于ruby-on-rails - 如何以 json 形式返回 Doorkeeper 访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24206483/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com