Usage | url-signer-rust | Spatie      

 SPATIE  

url-signer-rust
===============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Url-signer-rust](https://spatie.be/docs/url-signer-rust/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/url-signer-rust/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/url-signer-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/url-signer-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/url-signer-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/url-signer-rust/v1/usage)
- [ Testing ](https://spatie.be/docs/url-signer-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/url-signer-rust/v1/changelog)

 Usage
=====

###  On this page 

1. [ Generating URLs ](#content-generating-urls)
2. [ Validating URLs ](#content-validating-urls)
3. [ Custom keys and parameter names ](#content-custom-keys-and-parameter-names)
4. [ Writing custom signers ](#content-writing-custom-signers)
5. [ PHP compatibility ](#content-php-compatibility)
6. [ Testing the expiry boundary ](#content-testing-the-expiry-boundary)

A signer-object can sign URLs and validate signed URLs. A secret key is used to generate signatures.

```
use spatie_url_signer::Sha256UrlSigner;

let url_signer = Sha256UrlSigner::new("mysecretkey")?;
```

Generating URLs
-----------------------------------------------------------------------------------------------------

Signed URLs can be generated by providing a regular URL and an expiration date to the `sign` method. Use an absolute Unix timestamp in seconds where PHP accepts a `DateTimeInterface`.

```
let expiration_date = Expiration::Timestamp(now + 10 * 24 * 60 * 60);

let signed_url = url_signer.sign("https://myapp.com", expiration_date)?;

// The generated URL will be valid for 10 days.
```

If an integer is provided as expiration date, the URL will be valid for that amount of seconds.

```
let signed_url = url_signer.sign("https://myapp.com", 30)?;

// The generated URL will be valid for 30 seconds.
```

Past expirations return `Error::InvalidExpiration`. Zero seconds is allowed. An empty default key returns `Error::InvalidSignatureKey`. Rust checks timestamp overflow instead of relying on PHP's date parser.

Validating URLs
-----------------------------------------------------------------------------------------------------

To validate a signed URL, simply call the `validate()` method. This will return a boolean.

```
assert!(url_signer.validate(&signed_url));

let forged_url = signed_url.replace("myapp.com", "somewhereelse.com");
assert!(!url_signer.validate(&forged_url));
```

The expiration check is inclusive: a URL expiring at Unix second 100 is valid at second 100 and invalid at second 101. Malformed or missing expiration/signature values return `false`, including array-valued signing parameters. Signature comparison uses constant-time comparison for equal-length values.

Use a cryptographically random secret and keep it out of URLs, logs and source control. Signing does not encrypt the URL or prevent replay before expiration. Your application must enforce authorization and use HTTPS.

Custom keys and parameter names
-----------------------------------------------------------------------------------------------------------------------------------------------------

You can override the default key for an individual URL. Both sides must use the same key and parameter names.

```
let url_signer = Sha256UrlSigner::new("mysecretkey")?
    .with_parameter_names("until", "hash");

let signed_url = url_signer.sign_with_key("https://myapp.com", 30, "custom-key")?;
assert!(url_signer.validate_with_key(&signed_url, "custom-key"));
assert!(!url_signer.validate_with_key(&signed_url, "wrong-custom-key"));
```

Choose distinct plain names without spaces, dots or brackets. As in PHP, other names may be transformed by the query parser and produce unverifiable links. PHP permits an empty per-call key override; Rust preserves that behavior, but an empty key is not secure.

Writing custom signers
--------------------------------------------------------------------------------------------------------------------------

This package provides a signer that uses SHA256 to generate signatures. You can create your own signer by implementing `SignatureAlgorithm`. `UrlSigner::with_algorithm` supplies query handling, expiration and signature validation, corresponding to extending PHP's `AbstractUrlSigner` and implementing `createSignature`.

```
#[derive(Debug)]
struct CustomSigner;

impl SignatureAlgorithm for CustomSigner {
    fn create_signature(&self, url: &str, expiration: &str, key: &str) -> String {
        Sha256.create_signature(url, expiration, key)
    }
}

let url_signer = UrlSigner::with_algorithm("mysecretkey", CustomSigner)?;
let signed_url = url_signer.sign("https://myapp.com", 30)?;
```

`Md5UrlSigner` preserves PHP's deprecated MD5 algorithm for existing links. It is not HMAC-MD5. Use `Sha256UrlSigner` for new links.

PHP compatibility
-----------------------------------------------------------------------------------------------------------

The reference is [spatie/url-signer at 3cddceff31fcbffc19ee21e5abf7cbf6c196292e](https://github.com/spatie/url-signer/tree/3cddceff31fcbffc19ee21e5abf7cbf6c196292e), after v2.2.0. The committed fixtures and live differential CI tests exercise both implementations.

PHP behaviorRust API and verification`Sha256UrlSigner`: hex HMAC-SHA256 over `url::expiration``Sha256UrlSigner`, PHP fixtures and differential testsDeprecated MD5 over `url::expiration::key``Md5UrlSigner`, PHP fixtures and differential testsInteger seconds / `DateTimeInterface` absolute expiryInteger seconds / `Expiration::Timestamp`, expiry-boundary and error testsPer-call key and constructor parameter names`sign_with_key`, `validate_with_key`, `with_parameter_names`, differential testsCustom `createSignature` extension point`SignatureAlgorithm` with `UrlSigner::with_algorithm`, public API test and executable example`parse_str` / `http_build_query` formattingByte-preserving PHP query parser with RFC 1738 encoding, fixtures and seeded differential casesThe URL text before the first `?` stays unchanged: no added slash, hostname lowercasing, default-port removal or path cleanup. Query order is retained, duplicate scalar keys keep the last value, nested PHP arrays are rebuilt, spaces become `+`, and query names containing dots or spaces become underscores. Existing signature and expiration parameters are removed before signing.

Fragments deliberately follow PHP's string-based behavior rather than browser URL rules. For example, `https://myapp.com?x=value#section` becomes a query containing `x=value%23section`. With no `?`, `#section` stays in the base and the signing parameters follow it. Such a link can round-trip as text but a browser will not send its fragment to your server. Avoid fragments in signed links used by browsers.

PHP's `array_merge` renumbers top-level integer query keys when appending the signature. That can make PHP itself produce an unverifiable URL; Rust preserves the same output and validation result rather than silently signing a different URL.

Compatibility targets 64-bit PHP 8.3+ with default `arg_separator.input=&`, `arg_separator.output=&`, `max_input_vars=1000`, and `max_input_nesting_level=64`. PHP 8.2 assigns different appended array indices after negative keys; use explicit nonnegative indices for links shared with that runtime. Changing PHP's INI settings can change signatures. Rust strings must be UTF-8; percent-encoded arbitrary query bytes are preserved, but raw non-UTF-8 URL/key input is not representable. Deprecated PHP class/interface aliases and string helper methods are not reproduced; custom behavior uses the Rust trait instead.

Testing the expiry boundary
-----------------------------------------------------------------------------------------------------------------------------------------

Use `with_clock` to supply a clock returning Unix seconds. Production signers use the system clock.

```
let url_signer = Sha256UrlSigner::new("mysecretkey")?.with_clock(|| 100);
let signed_url = url_signer.sign("https://myapp.com", 0)?;
assert!(url_signer.validate(&signed_url));
assert!(!url_signer.with_clock(|| 101).validate(&signed_url));
```

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
