Skip to Content
DocsLoremind PlatformAuthentication

Authentication

LoreMind supports two authentication modes. Choose based on your game’s architecture.

Which Mode Should You Use?

ScenarioRecommended Mode
Production multiplayer gameServer Mediated
Game with player accountsServer Mediated
Prototype / proof of conceptDirect Client
Single-player gameDirect Client

Server Mediated gives you full control over access, lets you use your own auth system (Steam, Epic, custom), and enables player identity for features like long-term memory.

Direct Client is quick to set up with built-in safeguards - great for prototypes and single-player games where you don’t need player accounts.

Your game server authenticates with LoreMind using an API key and proxies NPC requests on behalf of players.

Benefits

BenefitDescription
Full controlYour server decides who can interact and when
Your auth systemIntegrate with Steam, Epic, custom accounts
Player identityTie interactions to authenticated players
Custom logicAdd your own validation, logging, limits
Secure key storageAPI key stays on your server

Note: Long-term memory requires Server Mediated mode with playerId. The client can’t be trusted to honestly identify itself.

Server Implementation

Here’s a complete example of integrating LoreMind into a C# game server:

using System.Net.Http; using System.Text; using System.Text.Json; public class LoreMindService { private readonly HttpClient _http; private readonly string _apiKey; public LoreMindService(string apiKey) { _apiKey = apiKey; _http = new HttpClient { BaseAddress = new Uri("https://loremind.peekgames.dev/api/loremind/v1/") }; _http.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}"); } public async Task<NPCResponse> GetNPCResponse( string playerId, string entityMindId, string playerMessage, GameContext gameContext) { var request = new { text = playerMessage, entityMindId = entityMindId, playerId = playerId, // For per-player rate limiting and memory memory = new { retrieve = true }, context = BuildRuntimeContext(gameContext) }; var json = JsonSerializer.Serialize(request); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await _http.PostAsync("npc/interact", content); if (!response.IsSuccessStatusCode) { var error = await response.Content.ReadAsStringAsync(); throw new LoreMindException($"API error: {error}"); } return await JsonSerializer.DeserializeAsync<NPCResponse>( await response.Content.ReadAsStreamAsync()); } private object BuildRuntimeContext(GameContext ctx) { // Build context from your game server's knowledge of the world return new { location = ctx.CurrentLocation?.Name, locationDetails = ctx.CurrentLocation?.Description, timeOfDay = ctx.WorldTime.ToTimeOfDay(), weather = ctx.Weather.ToString().ToLower(), nearbyCharacters = ctx.NearbyNPCs.Select(n => n.DisplayName).ToArray(), playerAppearance = ctx.Player.GetAppearanceDescription(), playerReputation = ctx.Player.GetReputationWith(ctx.CurrentNPC.Faction), situation = ctx.CurrentInteractionType, recentEvents = ctx.RecentWorldEvents.Take(5).ToArray() }; } }

Your Game Server API

Expose an endpoint for your Unity client to call:

// ASP.NET Core example [ApiController] [Route("api/npc")] public class NPCController : ControllerBase { private readonly LoreMindService _loreMind; private readonly IPlayerService _players; private readonly IGameStateService _gameState; [HttpPost("interact")] [Authorize] // Your auth - Steam, Epic, custom JWT, etc. public async Task<IActionResult> Interact([FromBody] NPCInteractRequest request) { // Get authenticated player from your auth system var playerId = User.GetPlayerId(); var player = await _players.GetPlayer(playerId); // Your rate limiting if (!await _rateLimiter.TryAcquire(playerId, "npc_interact")) { return StatusCode(429, "Too many requests"); } // Build context from your game state var gameContext = await _gameState.GetContextForPlayer(playerId); // Call LoreMind var response = await _loreMind.GetNPCResponse( playerId: playerId, entityMindId: request.EntityMindId, playerMessage: request.Message, gameContext: gameContext ); // Log for your analytics _analytics.TrackNPCInteraction(playerId, request.EntityMindId, response.Metadata); return Ok(new { response = response.Response, character = response.Character }); } }

Unity Client (Server Mediated)

The Unity client talks to your game server, not directly to LoreMind:

using UnityEngine; using UnityEngine.Networking; public class NPCClient : MonoBehaviour { [SerializeField] private string gameServerUrl = "https://api.yourgame.com"; public async Task<string> TalkToNPC(string entityMindId, string message) { var request = new { entityMindId, message }; var json = JsonUtility.ToJson(request); using var webRequest = new UnityWebRequest($"{gameServerUrl}/api/npc/interact", "POST"); webRequest.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(json)); webRequest.downloadHandler = new DownloadHandlerBuffer(); webRequest.SetRequestHeader("Content-Type", "application/json"); webRequest.SetRequestHeader("Authorization", $"Bearer {GetPlayerToken()}"); await webRequest.SendWebRequest(); if (webRequest.result != UnityWebRequest.Result.Success) { Debug.LogError($"NPC request failed: {webRequest.error}"); return null; } var response = JsonUtility.FromJson<NPCResponse>(webRequest.downloadHandler.text); return response.response; } private string GetPlayerToken() { // Return auth token from your player authentication system return PlayerAuth.CurrentToken; } }

Setting Up Server Mediated Mode

  1. Create a Server API Key

    • Go to loremind.peekgames.dev 
    • Navigate to Projects > Your Project > API Keys
    • Click Create API Key > Server Key
    • Copy immediately (shown only once)
  2. Configure Your Project

    • Go to Project Settings > Authentication
    • Select Server Mediated
    • Save changes
  3. Store the Key Securely

    • Use environment variables or a secrets manager
    • Never commit to version control
    • Never include in game builds
  4. Implement the Server Integration

    • See code examples above
    • Handle errors gracefully
    • Implement your own rate limiting layer

Rate Limiting

With Server Mediated mode, you have full control over rate limiting:

LoreMind’s limits (configurable safety net):

  • Per-player limits (when playerId is provided)
  • Per-project limits

Configure these in Dashboard → Project Settings → Rate Limits.

Your server’s limits (you control):

// Example: Custom rate limiting in your server if (player.NPCInteractionsToday > dailyLimit) { return TooManyRequests("Daily NPC limit reached"); } if (player.LastNPCInteraction > DateTime.UtcNow.AddSeconds(-cooldownSeconds)) { return TooManyRequests("Please wait before talking again"); }

Direct Client Mode

Unity clients authenticate directly with LoreMind using device-based tokens. Use only for prototypes or offline-capable single-player games.

When Direct Client Makes Sense

  • Rapid prototyping - Test NPC behavior before building server infrastructure
  • Single-player offline games - No server to proxy through
  • Game jams - Ship fast without server complexity

Limitations

  • No player identity - Device-based, not player-based
  • Limited context - Client doesn’t have full game state like a server does
  • Rate limiting is device-based - Harder to prevent abuse
  • API keys in builds - Project ID exposed (though not the server key)

Unity SDK (Direct Client)

using Peek.LoreMind; // SDK handles authentication automatically var npc = GetComponent<LoreMindNPC>(); var response = await npc.RespondAsync("Hello!");

The SDK:

  • Generates a device ID on first launch
  • Creates sessions automatically
  • Refreshes expired tokens transparently

Setting Up Direct Client

  1. Configure Project Settings

    • Open Window > LoreMind > Control Panel
    • Paste your Project ID
    • Set Auth Mode to Direct Client
  2. Configure Rate Limits in Dashboard

    • Go to Project Settings > Rate Limits
    • Set per-device limits appropriate for your game
    • Consider daily caps to prevent abuse

Editor API Keys

Editor keys allow Unity Editor tools to fetch Entity Minds and test configurations during development.

Format: sk_editor_...

Use for:

  • Entity Mind dropdown in Inspector
  • Lore import tools
  • Editor testing

Never include in builds. Use #if UNITY_EDITOR guards.


Security Best Practices

For Server Mediated (Production)

  1. API keys in secrets manager - AWS Secrets Manager, Azure Key Vault, HashiCorp Vault
  2. Rotate keys quarterly - Create new key, update servers, revoke old key
  3. Monitor usage - Set up alerts for unusual patterns
  4. Validate all player input - Don’t trust client-provided entity mind IDs
  5. Log everything - NPC interactions are game events worth tracking

For Direct Client (Prototyping)

  1. Configure strict rate limits - In dashboard, not client code
  2. Monitor credit usage - Set up billing alerts
  3. Plan migration to Server Mediated - Don’t ship production on Direct Client

Next Steps

Last updated on