Class: ApiSignature::Signer

Inherits:
Object
  • Object
show all
Defined in:
lib/api_signature/signer.rb

Overview

The signer requires secret key.

signer = ApiSignature::Signer.new('access key', 'secret key', uri_escape_path: true)

Constant Summary collapse

NAME =
'API-HMAC-SHA256'

Instance Method Summary collapse

Constructor Details

#initialize(access_key, secret_key, options = {}) ⇒ Signer

Options:

Parameters:

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :unsigned_headers (Array<String>) — default: []

    A list of headers that should not be signed. This is useful when a proxy modifies headers, such as ‘User-Agent’, invalidating a signature.

  • :uri_escape_path (Boolean) — default: true

    When ‘true`, the request URI path is uri-escaped as part of computing the canonical request string.

  • :apply_checksum_header (Boolean) — default: false

    When ‘true`, the computed content checksum is returned in the hash of signature headers.

  • :signature_header (String) — default: authorization

    Header name for signature

  • :service (String) — default: web

    Service name



31
32
33
34
35
# File 'lib/api_signature/signer.rb', line 31

def initialize(access_key, secret_key, options = {})
  @access_key = access_key
  @secret_key = secret_key
  @options = options
end

Instance Method Details

#sign_request(request) ⇒ Signature

Computes a signature. Returns the resultant signature as a hash of headers to apply to your HTTP request. The given request is not modified.

signature = signer.sign_request(
  http_method: 'PUT',
  url: 'https://domain.com',
  headers: {
    'Abc' => 'xyz',
  },
  body: 'body' # String or IO object
)

Parameters:

  • request (Hash)

Options Hash (request):

  • :http_method (required, String)

    One of ‘GET’, ‘HEAD’, ‘PUT’, ‘POST’, ‘PATCH’, or ‘DELETE’

  • :url (required, String, URI::HTTPS, URI::HTTP)

    The request URI. Must be a valid HTTP or HTTPS URI.

  • :headers (optional, Hash) — default: {}

    A hash of headers to sign. If the ‘X-Amz-Content-Sha256’ header is set, the ‘:body` is optional and will not be read.

  • :body (optional, String, IO) — default: 'X-Amz-Content-Sha256'ody. A sha256 checksum is computed of the body unless the 'X-Amz-Content-Sha256' header is set.

    ”) The HTTP request body. A sha256 checksum is computed of the body unless the ‘X-Amz-Content-Sha256’ header is set.

Returns:



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/api_signature/signer.rb', line 67

def sign_request(request)
  builder = Builder.new(request, unsigned_headers)
  sig_headers = builder.build_sign_headers(apply_checksum_header?)
  data = build_signature(builder)

  # apply signature
  sig_headers[signature_header_name] = data[:header]

  # Returning the signature components.
  Signature.new(data.merge!(headers: sig_headers))
end