Guides · BossCheck team · Updated 2026-10-14

How to Protect API Keys in a Unity Game

If a key is in your Unity build, players can get it. The goal isn't hiding keys in the client; it's making sure the client never needs a secret.

How keys get pulled out of Unity builds

With the Mono scripting backend, your game code ships as .NET assemblies (like Assembly-CSharp.dll) that free decompilers such as ILSpy or dnSpy turn back into readable C#. IL2CPP compiles code to native machine code, which is harder to read, but class names and every string literal are stored in a separate global-metadata.dat file. Community tools such as Il2CppDumper export all of those strings to a file in one step, and protected or encrypted metadata can often be dumped from memory while the game runs. Keys in ScriptableObject assets, Resources folders, StreamingAssets or JSON config files are even easier: they are just data in the build. Mobile and WebGL builds are no different, and players can also watch your game's network traffic with a proxy.

Sort your keys: public vs secret

The fix: a small backend holds the secret

Your Unity client calls an endpoint you control (a serverless function on Cloudflare Workers, Vercel, Firebase Cloud Functions, Supabase Edge Functions, or PlayFab CloudScript / Azure Functions). That endpoint checks who the player is, applies limits, and then uses the secret key, which lives only in the server's environment variables.

// Unity client: no secret here, just the player's session token
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class AiHint : MonoBehaviour {
    const string Endpoint = "https://api.yourgame.com/hint";
    public IEnumerator GetHint(string playerToken, string question) {
        var body = JsonUtility.ToJson(new HintReq { q = question });
        using var req = new UnityWebRequest(Endpoint, "POST");
        req.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(body));
        req.downloadHandler = new DownloadHandlerBuffer();
        req.SetRequestHeader("Content-Type", "application/json");
        req.SetRequestHeader("Authorization", "Bearer " + playerToken);
        yield return req.SendWebRequest();
        if (req.result == UnityWebRequest.Result.Success) Debug.Log(req.downloadHandler.text);
    }
    [System.Serializable] class HintReq { public string q; }
}
// Server (e.g. a Cloudflare Worker). OPENAI_API_KEY is a secret env var.
export default {
  async fetch(request, env) {
    const player = await verifyPlayerToken(request.headers.get("Authorization"), env);
    if (!player) return new Response("Unauthorized", { status: 401 });
    if (!(await underRateLimit(player.id, env))) return new Response("Slow down", { status: 429 });
    const { q } = await request.json();
    const r = await fetch("https://api.openai.com/v1/chat/completions", {
      method: "POST",
      headers: { "Authorization": `Bearer ${env.OPENAI_API_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({ model: "gpt-4o-mini", max_tokens: 200,
        messages: [{ role: "user", content: String(q).slice(0, 500) }] })
    });
    return new Response(await r.text(), { headers: { "Content-Type": "application/json" } });
  }
};

verifyPlayerToken and underRateLimit are yours to implement with whatever auth you use (Unity Authentication, PlayFab, Firebase Auth, Steam auth tickets). Without auth and rate limits, your endpoint just becomes a free proxy for your key.

Platform notes

What doesn't work

If a key already shipped

  1. Rotate or revoke it at the provider immediately; old builds will keep leaking it.
  2. Move the call behind a backend and ship an update.
  3. Check provider dashboards for unusual usage and set spending caps.

Prompt to paste into your AI coding tool

Search this Unity project (scripts, ScriptableObjects, Resources, StreamingAssets,
config files and PlayFab settings) for API keys, tokens and secrets. Classify each
as public-by-design or secret. For every secret, create a server-side function that
reads it from an environment variable, requires player authentication and applies
a rate limit, and change the Unity code to call that function instead.

Want this checked automatically?

BossCheck is a security scanner for indie games built with AI tools. It's in pre-launch: join the waitlist for early access.

Join the waitlist →

FAQ

Can I hide an API key in a Unity build with IL2CPP?

No. IL2CPP makes reverse engineering harder, but string literals live in global-metadata.dat and can be extracted with free tools. Treat any key in the build as public.

Is my Firebase API key in Unity a security risk?

No. The Firebase client API key is meant to be public. Protect your data with Security Rules and, optionally, App Check.

Where should I store an OpenAI key for my Unity game?

On a server or serverless function that authenticates players and rate-limits requests. The Unity client calls your function, never OpenAI directly.

Is the PlayFab Title ID secret?

No. The Title ID is public. The Developer Secret Key is the secret and must only be used on servers or in CloudScript.

More guides