After successful authentication, Hanko generates a session token that is stored as a cookie. Use the session token to authenticate requests to your backend. This guide shows how to implement session token validation in Rust to ensure that only authenticated users can access your application’s protected resources.

Get the Hanko API URL

Retrieve the API URL from the Hanko console.
If you are self-hosting Hanko you need to provide your own URL.

Steps to Authenticate Requests

  1. Retrieve the Session Token.
  2. Verify the Session token using the Hanko Validate API endpoint.

Session Token Validation Function

The following code demonstrates how to validate session tokens against the Hanko backend. The implementation for retrieving the session token cookie will vary depending on your web framework.
use reqwest::Client;
use serde::{Deserialize, Serialize};

// Configuration constants
struct Config {
    hanko_api_url: String,
}

impl Config {
    fn new() -> Self {
        Self {
            hanko_api_url: std::env::var("HANKO_API_URL")
                .unwrap_or_else(|_| "YOUR_HANKO_API_URL".to_string()),
        }
    }
}

// Types
#[derive(Serialize)]
struct ValidationPayload<'a> {
    session_token: &'a str,
}

#[derive(Deserialize)]
struct ValidationResponse {
    is_valid: bool,
}

async fn validate_token(token: &str, client: &Client, config: &Config) -> Result<bool, reqwest::Error> {
    let payload = ValidationPayload { session_token: token };
    let url = format!("{}/sessions/validate", config.hanko_api_url);

    let resp = client.post(&url).json(&payload).send().await?;

    if !resp.status().is_success() {
        return Ok(false);
    }

    let validation_data: ValidationResponse = resp.json().await?;
    Ok(validation_data.is_valid)
}