简体   繁体   English

扩展Doorkeeper TokenResponse类

[英]Extending Doorkeeper TokenResponse class

I need to extend Doorkeeper::OAuth::TokenResponse class because I want to add something to returned data. 我需要扩展Doorkeeper::OAuth::TokenResponse类,因为我想在返回的数据中添加一些内容。 By default that class creates a return body like this: 默认情况下,该类创建一个返回主体,如下所示:

{
  "access_token": "...",
  "token_type": "bearer",
  "expires_in": 7200,
  "refresh_token": "...",
  "scope": "some_scope"
}

I'd like to keep that and add a new field: 我想保留该内容并添加一个新字段:

{
  "access_token": "...",
  "token_type": "bearer",
  "expires_in": 7200,
  "refresh_token": "...",
  "scope": "some_scope",
  "my_custom_field": 47
}

Can I do that without monkey patching TokenResponse class? 我可以不用猴子修补TokenResponse类来做到这TokenResponse吗? If not, is there anything I can do to improve my current implementation (for better compatibility with new versions of Doorkeeper and etc.)? 如果没有,我可以做些什么来改善当前的实现(以更好地与新版本的Doorkeeper等兼容)? Here is my current implementation: 这是我当前的实现:

module Doorkeeper
  module OAuth
    class TokenResponse
      old_body = instance_method(:body)

      define_method(:body) do
        body = old_body.bind(self).()
        if self.token.scopes.include? 'some_scope'
          body[:my_custom_field] = 47
        end
        body
      end
    end
  end
end

I do have tests for that functionality so I will know if upgrading Doorkeeper gem breaks it. 我确实对该功能进行了测试,所以我会知道升级Doorkeeper gem是否会破坏它。

Yes, you do not need to monkey patch. 是的,您不需要猴子补丁。 There are a few things you can try. 您可以尝试一些方法。

  1. Fork the gem and make changes in your fork, while making sure to update your fork when there is a change. 分叉宝石并在叉子中进行更改,同时确保在有更改时更新叉子。

    1. Go to github and fork the Doorkeeper Gem: https://github.com/doorkeeper-gem/doorkeeper . 转到github并分叉Doorkeeper Gem: https : //github.com/doorkeeper-gem/doorkeeper
    2. If you're using a Gemfile for your Ruby project, be sure to point to your fork of the gem, eg 如果您在Ruby项目中使用Gemfile,请确保指向您的gem分支,例如

       gem 'doorkeeper', github: 'USERNAME/doorkeeper' 
  2. If the change in your fork with the custom field is generic enough, do a pull request, but chances are this won't work, since the hash is for an OAuth Token Response. 如果您使用自定义字段在派生中所做的更改足够通用,请执行拉取请求,但由于哈希值是针对OAuth令牌响应的,因此这可能不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM