Skip to content

Create and verify signed urls. Supports expiration time.

License

Notifications You must be signed in to change notification settings

fnando/url_signature

Repository files navigation

URL Signature

Create and verify signed urls. Supports expiration time.

Tests Code Climate Version Downloads

Installation

gem install url_signature

Or add the following line to your project's Gemfile:

gem "url_signature"

Usage

To create a signed url, you can use SignedURL.call(url, **kwargs), where arguments are:

  • key: The secret key that will be used to generate the HMAC digest.
  • params: Any additional params you want to add as query strings.
  • expires: Any integer representing an epoch time. Urls won't be verified after this date. By default, urls don't expire.
  • hmac_proc: Proc that will generate the signature. By default, it generates a base64url(sha512_hmac(data)) signature (with no padding). The proc will be called with two parameters: key and data.
  • signature_param: The signature's param name. By default it's signature.
  • expires_param: The expires' param name. By default it's expires.
key = "secret"

signed_url = SignedURL.call("https://nandovieira.com", key: key)
#=> "https://nandovieira.com/?signature=87fdf44a5109c54edff2e0258b354e32ba5b..."

You can use the method SignedURL.verified?(url, **kwargs) to verify if a signed url is valid.

key = "secret"

signed_url = SignedURL.call("https://nandovieira.com", key: key)

SignedURL.verified?(signed_url, key: key)
#=> true

Alternatively, you can use SignedURL.verify!(url, **kwargs), which will raise exceptions if a url cannot be verified (e.g. has been tampered, it's not fresh, or is a plain invalid url).

  • URLSignature::InvalidURL if url is not valid
  • URLSignature::ExpiredURL if url has expired
  • URLSignature::InvalidSignature if the signature cannot be verified

To create a url that's valid for a time window, use :expires. The following example create a url that's valid for 2 minutes.

key = "secret"

signed_url = SignedURL.call(
  "https://nandovieira.com",
  key: secret,
  expires: Time.now.to_i + 120
)
#=> "https://nandovieira.com/?expires=1604477596&signature=7ac5eaee20d316..."

Maintainer

Contributors

Contributing

For more details about how to contribute, please read https://github.com/fnando/url_signature/blob/main/CONTRIBUTING.md.

License

The gem is available as open source under the terms of the MIT License. A copy of the license can be found at https://github.com/fnando/url_signature/blob/main/LICENSE.md.

Code of Conduct

Everyone interacting in the url_signature project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.