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 demonstrates how to implement session token validation in Python to ensure that only properly 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.

Example function

The following section demonstrates how to validate session tokens against the Hanko backend. The specific implementation for retrieving the session token cookie will vary depending on your framework.
def validate_session_token(token: str) -> Tuple[bool, Optional[str]]:
    """
    Validates a session token with the Hanko API.
    Returns a tuple of (is_valid: bool, error_message: Optional[str])
    """
    try:
        response = requests.post(
            f"{HANKO_API_URL}/sessions/validate",
            json={"session_token": token}
        )

        if response.status_code != 200:
            return False, "Invalid token"

        validation_data = response.json()
        if not validation_data.get("is_valid", False):
            return False, "Invalid token"

        return True, None

    except requests.Timeout:
        return False, "Authentication service timeout"
    except requests.RequestException:
        return False, "Authentication service unavailable"