Sha256: 825cf3dc0fdeb7cef7b374286c50f2408de69f2e40e12a5ddf19355fef610206

Contents?: true

Size: 1.83 KB

Versions: 1

Compression:

Stored size: 1.83 KB

Contents

# frozen_string_literal: true

require 'json'
require 'jwt'
require 'net/http'
require 'uri'

module Tikkie
  module Api
    module V1
      # Provides authentication for the ABN AMRO OAuth API.
      # see https://developer.abnamro.com/get-started#authentication
      class Authentication
        def initialize(config)
          @config = config
        end

        def authenticate
          uri = URI.parse(File.join(@config.api_url, "/oauth/token"))

          request = Net::HTTP::Post.new(uri)
          request["Api-Key"] = @config.api_key

          request.set_form_data(
            client_assertion: jwt_token,
            client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
            grant_type: "client_credentials",
            scope: "tikkie"
          )

          response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
            http.request(request)
          end

          if response.is_a?(Net::HTTPSuccess)
            json = JSON.parse(response.body, symbolize_names: true)

            Tikkie::Api::V1::AccessToken.new(json[:access_token], json[:expires_in])
          else
            raise Tikkie::Api::V1::AuthenticationException, response
          end
        end

        private

        def jwt_token
          now = Time.now.to_i

          payload = {
            nbf: now - 120,
            exp: now + 120, # Token is valid for 2 minutes
            iss: "Ruby Tikkie client",
            sub: @config.api_key,
            aud: @config.oauth_token_url
          }

          # Send header typ as String, not symbol (JWT version 1.x adds "typ" as String by default).
          headers = {
            "typ" => "JWT"
          }

          JWT.encode(payload, @config.private_data, @config.jwt_hashing_algorithm, headers)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tikkie-api-2.0.0 lib/tikkie/api/v1/authentication.rb