Crate signed_tokens

Crate signed_tokens 

Source
Expand description

A simple Rust crate for creating and verifying HMAC-signed tokens, with multiple rotating keys.

The canonical use-case for this is authenticated session tokens. After a user successfully signs in, your system should:

  1. Generate a random session ID, perhaps using the uuid crate
  2. Put the account information into a cache (e.g., Redis) using the session ID as the key
  3. Use the sign function to create a digitally-signed token containing the session ID and the HMAC digital signature
  4. Include the signed token as a secure, HTTP-only cookie

For example:

use std::env;
use signed_tokens::SigningKey;

 
// get your signing keys from env vars, or a secrets service
let signing_keys = vec![
    SigningKey::new(env::var("SESSION_SIGNING_KEY_1").unwrap()),
    SigningKey::new(env::var("SESSION_SIGNING_KEY_2").unwrap()),
    SigningKey::new(env::var("SESSION_SIGNING_KEY_3").unwrap()),
];

// generate a new session ID
let session_id = "... some unique session id ... ";

// sign it to create a token
let token = signed_tokens::sign(&session_id, &signing_keys)?;

// set a Secure HttpOnly response cookie 
// to the value of token.to_string()...

When you receive the token in a subsequent request, use the verify function to verify it.

 
// read `token_from_request_cookie` from the request cookies,
// and use the same `signing_keys` from above
let verified_token = signed_tokens::verify(&token_from_request_cookie, &signing_keys)?;
let session_id = verified_token.payload();
 
// fetch account info from your cache using session_id...

Structs§

SignedToken
Represents a signed token. Use the to_string method to encode the token as a URL-safe base64 string.
SigningKey
Represents a key that can be used when building an HMAC digital signature.
VerifiedToken
Represents a verified token.

Enums§

SignError
Potential errors returned from the sign function.
SigningKeyStatus
Indicates the status of a SigningKey.
VerifyError
Potential errors returned from the verify function.

Functions§

sign
Signs the given payload using a randomly selected active key from the signing_keys.
verify
Verifies a previously signed token. The key used to sign the token must still be in the signing_keys array at the same index. If the token has been tampered with, the Result will contain a VerifyError::Signature error.