Create and verify signed urls. Supports expiration time.
Create and verify signed urls. Supports expiration time.
gem install url_signature
Or add the following line to your project’s Gemfile:
gem "url_signature"
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 verifiedhmac_proc
: Proc
that will generate the signature. By default, it generatesbase64url(sha512_hmac(data))
signature (with no padding). The proc will bekey
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 validURLSignature::ExpiredURL
if url has expiredURLSignature::InvalidSignature
if the signature cannot be verifiedTo 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..."
For more details about how to contribute, please read
https://github.com/fnando/url_signature/blob/main/CONTRIBUTING.md.
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.
Everyone interacting in the url_signature project’s codebases, issue trackers,
chat rooms and mailing lists is expected to follow the
code of conduct.