@@ -59,6 +59,16 @@ class Configuration
5959 # @return [String]
6060 attr_accessor :password
6161
62+ # Defines the client ID used with OAuth2.
63+ #
64+ # @return [String]
65+ attr_accessor :client_id
66+
67+ # Defines the client secret used with OAuth2.
68+ #
69+ # @return [String]
70+ attr_accessor :client_secret
71+
6272 # Defines the access token (Bearer) used with OAuth2.
6373 attr_accessor :access_token
6474
@@ -182,6 +192,31 @@ def initialize
182192 @inject_format = false
183193 @force_ending_format = false
184194 @logger = defined? ( Rails ) ? Rails . logger : Logger . new ( STDOUT )
195+ @access_token_expires_at = nil
196+ @access_token_getter = Proc . new {
197+ access_token_valid = @access_token && @access_token_expires_at > Time . now + 60
198+ next @access_token if access_token_valid
199+
200+ puts "Refreshing access token..." if @debugging
201+ # obtain new access token using client credentials
202+ token_url = 'https://api.bandwidth.com/api/v1/oauth2/token'
203+ auth_header = 'Basic ' + [ "#{ @client_id } :#{ @client_secret } " ] . pack ( 'm' ) . delete ( "\r \n " )
204+ conn = Faraday . new ( url : token_url ) do |faraday |
205+ faraday . request :url_encoded
206+ faraday . adapter Faraday . default_adapter
207+ end
208+ response = conn . post do |req |
209+ req . headers [ 'Authorization' ] = auth_header
210+ req . headers [ 'Content-Type' ] = 'application/x-www-form-urlencoded'
211+ req . body = 'grant_type=client_credentials'
212+ end
213+ if response . status != 200
214+ raise "Failed to obtain access token: #{ response . status } #{ response . body } "
215+ end
216+ body = JSON . parse ( response . body )
217+ @access_token = body [ 'access_token' ]
218+ @access_token_expires_at = Time . now + body [ 'expires_in' ]
219+ }
185220
186221 yield ( self ) if block_given?
187222 end
@@ -237,6 +272,7 @@ def api_key_with_prefix(param_name, param_alias = nil)
237272 # Gets access_token using access_token_getter or uses the static access_token
238273 def access_token_with_refresh
239274 return access_token if access_token_getter . nil?
275+ return unless @client_id && @client_secret
240276 access_token_getter . call
241277 end
242278
@@ -245,6 +281,12 @@ def basic_auth_token
245281 'Basic ' + [ "#{ username } :#{ password } " ] . pack ( 'm' ) . delete ( "\r \n " )
246282 end
247283
284+ # Gets Bearer auth token string
285+ def oauth_bearer_token
286+ "Bearer #{ access_token_with_refresh } " unless access_token_with_refresh . nil?
287+ end
288+
289+
248290 # Returns Auth Settings hash for api client.
249291 def auth_settings
250292 {
@@ -260,7 +302,7 @@ def auth_settings
260302 type : 'oauth2' ,
261303 in : 'header' ,
262304 key : 'Authorization' ,
263- value : "Bearer #{ access_token_with_refresh } "
305+ value : oauth_bearer_token
264306 } ,
265307 }
266308 end
0 commit comments