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
- OK to ship (designed to be public): Firebase config / Android and iOS API keys, Supabase anon or publishable key, PlayFab Title ID, Unity project IDs, Steam App ID, analytics write keys. These identify your project; your server rules protect the data.
- Never ship: PlayFab Developer Secret Key, Supabase
service_rolekey, Firebase Admin service account JSON, Steam publisher Web API key, Stripe secret key, OpenAI/Anthropic API keys, Discord bot tokens, cloud (AWS/GCP/Azure) credentials.
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
- PlayFab: the client SDK only needs the Title ID. The Developer Secret Key unlocks the Server and Admin APIs, and Microsoft's docs say to never include it in a client build. Keep it in CloudScript or your own server, and make sure the secret key field in the SDK's PlayFab settings asset is empty when you build the client (PlayFab Unity SDK setup). If it ever shipped, rotate it on the Secret Keys page in Game Manager.
- In-app purchases: validate receipts on your server (Google Play Developer API, App Store Server API, or your IAP provider's server-side validation) before granting items.
- Steam: see keeping your Steam Web API key out of your build.
- Firebase / Supabase: the client keys are public, so your rules matter. See security rules for multiplayer games.
What doesn't work
- Obfuscators and encrypting the key: the game has to decrypt it to use it, so the decrypted key is in memory for anyone to read.
- Splitting the key into pieces: same problem, it just takes slightly longer.
- Git-ignoring a config file: keeps it out of the repo, but if it's in
Assets/, it still ends up in the build.
If a key already shipped
- Rotate or revoke it at the provider immediately; old builds will keep leaking it.
- Move the call behind a backend and ship an update.
- 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
- How to Keep Your Steam Web API Key Out of Your Game Build
- Firebase and Supabase Security Rules for Multiplayer Games
- Never Trust the Client: Stopping Cheaters in Vibe-Coded Multiplayer Games
- Security Checklist Before Shipping a Game Built with Cursor, Claude or Lovable
- Is Code from Cursor, Lovable or Claude Secure? What to Check Before You Ship
- How to Stop Players Editing Browser Game Saves to Unlock Paid Items
- Securing Godot 4 Multiplayer: RPCs, Authority and Server-Side Validation
- Is My Vibe-Coded Game Safe? A Free 10-Minute Security Self-Check
- Stop Bots and Scripts from Breaking Your Game Economy Before a Steam Launch