validate_hmac_token_ctx

Function validate_hmac_token_ctx 

Source
pub fn validate_hmac_token_ctx(
    class: TokenClass,
    id: &str,
    token: &[u8],
    secret: &[u8],
) -> Result<bool, Error>
Expand description

Verifies an HMAC-protected CSRF token for a given class and identifier.

Accepts tokens in the HEX_HMAC.RANDOM format produced by generate_hmac_token_ctx. Returns Ok(true) on a valid token and Ok(false) on structural or verification failure. Returns an Err only for malformed UTF-8 or hex-decoding errors while parsing.

The token is recomputed as HMAC-SHA256 over "{class}|{id}|{RANDOM}" using the provided secret and compared in constant time.

§Errors

  • Returns Err if token is not valid UTF-8.
  • Returns Err if the HMAC hex part cannot be decoded.

§Examples

use actix_csrf_middleware::{
    generate_hmac_token_ctx, validate_hmac_token_ctx, TokenClass
};

let sid = "SID-xyz";
let secret = b"application-secret-at-least-32-bytes-long";
let token = generate_hmac_token_ctx(TokenClass::Authorized, sid, secret);

assert!(validate_hmac_token_ctx(TokenClass::Authorized, sid, token.as_bytes(), secret).unwrap());

// Wrong class or id will fail verification
assert!(!validate_hmac_token_ctx(TokenClass::Anonymous, sid, token.as_bytes(), secret).unwrap());
assert!(!validate_hmac_token_ctx(TokenClass::Authorized, "SID-other", token.as_bytes(), secret).unwrap());