Class: OpenFga::TokenManager::Oauth2TokenManager
- Inherits:
-
Object
- Object
- OpenFga::TokenManager::Oauth2TokenManager
- Defined in:
- lib/openfga/token_manager/token_manager.rb
Overview
Oauth2TokenManager uses the /oauth/token endpoint on a token issuer to fetch a new token using the Oauth2 standard.
Defined Under Namespace
Classes: Config
Instance Attribute Summary collapse
-
#config ⇒ Object
readonly
Returns the value of attribute config.
Instance Method Summary collapse
- #access_token ⇒ Object
-
#initialize(config) ⇒ Oauth2TokenManager
constructor
A new instance of Oauth2TokenManager.
Constructor Details
#initialize(config) ⇒ Oauth2TokenManager
Returns a new instance of Oauth2TokenManager.
54 55 56 57 58 59 |
# File 'lib/openfga/token_manager/token_manager.rb', line 54 def initialize(config) @config = config @access_token_expires_at = nil @access_token = nil @logger = config.logger || Logger.new($stdout) end |
Instance Attribute Details
#config ⇒ Object (readonly)
Returns the value of attribute config.
52 53 54 |
# File 'lib/openfga/token_manager/token_manager.rb', line 52 def config @config end |
Instance Method Details
#access_token ⇒ Object
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/openfga/token_manager/token_manager.rb', line 61 def access_token if @access_token_expires_at && @access_token_expires_at > (Time.now.utc + 60) return @access_token end @logger.info "Refreshing access token from #{@config.token_issuer}" form_data = { 'grant_type' => 'client_credentials', 'client_id' => @config.client_id, 'client_secret' => @config.client_secret } if @config.audience form_data['audience'] = @config.audience end uri = URI.parse("https://#{@config.token_issuer}/oauth/token") request = Net::HTTP::Post.new(uri) request.set_form_data(form_data) = { use_ssl: uri.scheme == 'https' } response = Net::HTTP.start(uri.hostname, uri.port, ) do |http| http.request(request) end if response.code.to_i == 200 body = JSON.parse(response.body) @access_token = body['access_token'] @access_token_expires_at = Time.now.utc + body['expires_in'].to_i @logger.info "Obtained new access token, expires at #{@access_token_expires_at}" @access_token else raise TokenRefreshError.new("Failed to obtain access token: #{response.code} #{response.body}") end end |