そこで、Rails 4 アプリでドアキーパーを使用し、Ruby ユーザーを支援するための API ラッパーを作成しました。ほとんどすべてが想定どおりに機能します。次のような OAuth2 クライアントを追加しました。
require 'oauth2-client'
module MyApiWrapper
class OAuth2Client < OAuth2Client::Client
SITE_URL = 'https://myapp.com'
TOKEN_PATH = '/oauth/token'
AUTHORIZE_PATH = '/oauth/authorize'
def initialize(client_id, client_secret, opts={})
site_url = opts.delete(:site_url) || SITE_URL
opts[:token_path] ||= TOKEN_PATH
opts[:authorize_path] ||= AUTHORIZE_PATH
super(site_url, client_id, client_secret, opts)
yield self if block_given?
self
end
...
def refresh!(token, opts={})
opts[:authenticate] = :body
refresh_token.get_token(token, opts)
end
end
end
最初に OAuth2Client のインスタンスを作成してユーザーを承認すると、次のようになります。
client = MyApiWrapper::OAuth2Client.new(ENV['CLIENT_ID'], ENV['CLIENT_SECRET'])
response = client.exchange_auth_code_for_token(:params => {
:code => params[:code],
:redirect_uri => 'http://localhost:3000/auth/myapp/callback'
})
token = JSON.parse response.body
access_token = token["access_token"]
@refresh_token = token["refresh_token"]
想定どおりにトークン ペア (refresh_token を使用) で応答します。以前と同じ OAuth2Client インスタンスを使用して、次のようにトークンを正常に更新して、新しいトークン ペアを取得できます。
response = client.refresh!(@refresh_token)
ただし、OAuth2Client の新しいインスタンスで同じことを実行しようとすると (後で、または別のコントローラーなどで)、ドアキーパーから次のエラー応答が返されます。
The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed.