🐾PurrNet Docs
Advanced

Authentication

PurrNet's authentication system validates each connecting client before they are allowed to participate in the game. Subclass AuthenticationBehaviour to supply credentials from the client and validate them on the server.

ClientServerGame
Client credentials pass validation — connection accepted

How it works

When a client connects, PurrNet calls GetClientPayload() on the client side. The returned payload (any serializable type) is sent to the server, where ValidateClientPayload() runs. Based on the result, the server either accepts the client into the session or sends back a denial payload and closes the connection.

The authentication exchange happens before any game objects are spawned or state is replicated, so unauthenticated clients never see game data.

API reference

ParameterTypeDefaultDescription
AuthenticationResponse.Accept()static AuthenticationResponse—Returns an accepted response. The client is allowed to join the session and will receive the full game state.
AuthenticationResponse.Deny(TDenial reason)static AuthenticationResponse—Returns a denial response with a typed reason payload. The reason is serialized and sent back to the client before the connection is closed.
GetClientPayload()abstract TPayload—Runs on the client. Build and return the credentials object to be sent to the server (e.g. a token, username+password hash, or steam ticket).
ValidateClientPayload(PlayerID conn, TPayload payload)abstract AuthenticationResponse—Runs on the server. Inspect the received payload and return Accept() or Deny(reason). Throw an exception to deny with a generic error.
UnAuthenticateClient(PlayerID conn)virtual void—Runs on the server when an authenticated client disconnects. Use to release server-side resources associated with that connection.

Basic example — password-protected server

PasswordAuth.cs
using PurrNet;
using UnityEngine;

// TPayload = what the client sends; TDenial = what the server sends back on failure
public class PasswordAuth : AuthenticationBehaviour<PasswordPayload, DenialReason>
{
    [SerializeField] private string _serverPassword = "supersecret";

    // Runs on the CLIENT — assemble the credentials
    public override PasswordPayload GetClientPayload()
    {
        return new PasswordPayload
        {
            // In production use a salted hash, never plaintext
            passwordHash = HashUtil.SHA256(PlayerPrefs.GetString("ServerPassword", "")),
            clientVersion = Application.version,
        };
    }

    // Runs on the SERVER — validate and return Accept or Deny
    public override AuthenticationResponse ValidateClientPayload(
        PlayerID conn, PasswordPayload payload)
    {
        string expectedHash = HashUtil.SHA256(_serverPassword);

        if (payload.clientVersion != Application.version)
            return AuthenticationResponse.Deny(DenialReason.VersionMismatch);

        if (payload.passwordHash != expectedHash)
            return AuthenticationResponse.Deny(DenialReason.WrongPassword);

        return AuthenticationResponse.Accept();
    }

    // Runs on the SERVER when an authenticated client leaves
    public override void UnAuthenticateClient(PlayerID conn)
    {
        Debug.Log($"Client {conn} disconnected — releasing auth record.");
        // Release any server-side session data for this connection
    }
}

[System.Serializable]
public struct PasswordPayload : IPackedAuto
{
    public string passwordHash;
    public string clientVersion;
}

public enum DenialReason
{
    WrongPassword,
    VersionMismatch,
    ServerFull,
    Banned,
}

Listening for denial on the client

Subscribe to networkManager.onAuthenticationDenied to receive the denial reason and show the player an appropriate UI message.

ConnectionUI.cs
using PurrNet;
using UnityEngine;
using TMPro;

public class ConnectionUI : MonoBehaviour
{
    [SerializeField] private NetworkManager _networkManager;
    [SerializeField] private GameObject     _deniedPanel;
    [SerializeField] private TextMeshProUGUI _deniedMessage;

    private void OnEnable()
    {
        // Fired on the client when the server sends a Deny() response
        _networkManager.onAuthenticationDenied += HandleDenied;
    }

    private void OnDisable()
    {
        _networkManager.onAuthenticationDenied -= HandleDenied;
    }

    private void HandleDenied(object reason)
    {
        _deniedPanel.SetActive(true);

        _deniedMessage.text = reason switch
        {
            DenialReason.WrongPassword    => "Incorrect server password.",
            DenialReason.VersionMismatch  => "Game version mismatch. Please update.",
            DenialReason.ServerFull       => "Server is full.",
            DenialReason.Banned           => "You have been banned from this server.",
            _                             => "Connection denied.",
        };
    }
}

Situational example — JWT token authentication

For online games with an account backend, the client fetches a short-lived JWT from your auth service before connecting. The server verifies the signature without contacting the auth service on every connection, making validation fast and stateless.

JwtAuth.cs
using PurrNet;
using UnityEngine;

public class JwtAuth : AuthenticationBehaviour<JwtPayload, string>
{
    // Populated by your login flow before the player connects
    public static string cachedToken;

    public override JwtPayload GetClientPayload()
    {
        return new JwtPayload { jwtToken = cachedToken ?? string.Empty };
    }

    public override AuthenticationResponse ValidateClientPayload(
        PlayerID conn, JwtPayload payload)
    {
        if (string.IsNullOrEmpty(payload.jwtToken))
            return AuthenticationResponse.Deny("No token provided.");

        // JwtValidator uses your public key to verify the signature locally
        if (!JwtValidator.TryValidate(payload.jwtToken, out string userId))
            return AuthenticationResponse.Deny("Invalid or expired token.");

        // Store userId for this connection — available in game systems
        AuthRegistry.Register(conn, userId);
        return AuthenticationResponse.Accept();
    }

    public override void UnAuthenticateClient(PlayerID conn)
    {
        AuthRegistry.Remove(conn);
    }
}

[System.Serializable]
public struct JwtPayload : IPackedAuto
{
    public string jwtToken;
}

Never send plain-text passwords

Always hash passwords client-side before transmitting them. Even over an encrypted transport, plain passwords can be extracted from memory or log files. Use a one-way hash (SHA-256 with a salt at minimum) or, better, a proper token-based scheme like JWT.

Short-lived tokens reduce risk

For account-based games, issue a short-lived session token (10–60 minutes) from your auth backend after login. The client uses that token as the payload. If a token is stolen, it expires quickly, limiting the blast radius.

Authentication fires before spawn

The authentication exchange completes before OnSpawned fires on any game object. This means unauthenticated clients never receive scene state, player positions, or SyncVar values — not even partially.