Module: HTTPX::Plugins::OAuth::InstanceMethods

Defined in:
lib/httpx/plugins/oauth.rb

Instance Method Summary collapse

Instance Method Details

#build_requestObject



158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/httpx/plugins/oauth.rb', line 158

def build_request(*)
  request = super

  return request if request.headers.key?("authorization")

  oauth_session = @options.oauth_session

  return request unless oauth_session && oauth_session.access_token

  request.headers["authorization"] = "Bearer #{oauth_session.access_token}"

  request
end

#oauth_auth(**args) ⇒ Object



114
115
116
# File 'lib/httpx/plugins/oauth.rb', line 114

def oauth_auth(**args)
  with(oauth_session: OAuthSession.new(**args))
end

#with_access_tokenObject



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/httpx/plugins/oauth.rb', line 118

def with_access_token
  oauth_session = @options.oauth_session

  oauth_session.load(self)

  grant_type = oauth_session.grant_type

  headers = {}
  form_post = { "grant_type" => grant_type, "scope" => Array(oauth_session.scope).join(" ") }.compact

  # auth
  case oauth_session.token_endpoint_auth_method
  when "client_secret_post"
    form_post["client_id"] = oauth_session.client_id
    form_post["client_secret"] = oauth_session.client_secret
  when "client_secret_basic"
    headers["authorization"] = Authentication::Basic.new(oauth_session.client_id, oauth_session.client_secret).authenticate
  end

  case grant_type
  when "client_credentials"
    # do nothing
  when "refresh_token"
    form_post["refresh_token"] = oauth_session.refresh_token
  end

  token_request = build_request("POST", oauth_session.token_endpoint, headers: headers, form: form_post)
  token_request.headers.delete("authorization") unless oauth_session.token_endpoint_auth_method == "client_secret_basic"

  token_response = request(token_request)
  token_response.raise_for_status

  payload = token_response.json

  access_token = payload["access_token"]
  refresh_token = payload["refresh_token"]

  with(oauth_session: oauth_session.merge(access_token: access_token, refresh_token: refresh_token))
end