pub fn generate_random_token() -> String
Expand description
Generates a cryptographically secure random CSRF token.
The token is 32 bytes of randomness, encoded with URL-safe base64 without padding
(aka base64url), resulting in a 43-character ASCII string. The alphabet is limited to
A-Z
, a-z
, 0-9
, -
, and _
, making it safe for use in URLs, HTTP headers, and
HTML form fields without additional escaping.
This function returns a standalone random value and does not bind the token to any
session or identity. For the Double-Submit Cookie pattern used by this crate, prefer
generate_hmac_token_ctx
which derives an HMAC-protected token from a session id
and the token, making it unforgeable by clients.
§Security
- The token is generated using a CSPRNG and is suitable for CSRF defenses.
- When using the Double-Submit Cookie pattern, do not place this raw token into a
cookie by itself. Use
generate_hmac_token_ctx
so the server can verify integrity. - When using the Synchronizer Token pattern (feature
actix-session
), this raw token may be stored server-side in session and compared using constant-time equality.
§Examples
Generate a token and validate its shape.
let tok = actix_csrf_middleware::generate_random_token();
assert_eq!(tok.len(), 43, "32 bytes base64url-encoded -> 43 chars");
assert!(tok.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'));
Produce an HMAC-protected token for Double-Submit Cookie flows.
use actix_csrf_middleware::{generate_random_token, generate_hmac_token_ctx, TokenClass};
let session_id = "SID-123";
let secret = b"an-application-wide-secret-at-least-32-bytes-long";
let raw = generate_random_token();
// In typical flows you would call `generate_hmac_token_ctx` directly without
// generating the raw token yourself; shown here for illustration.
let hmac_token = generate_hmac_token_ctx(TokenClass::Authorized, session_id, secret);
assert!(hmac_token.contains('.'));
let parts: Vec<_> = hmac_token.split('.').collect();
assert_eq!(parts.len(), 2);