MultiConnectMultiConnectDocs Website home
MultiConnectSDK › SDK Apps

6. Server access

Why servers need their own credential

The SDK key is inside every copy of your game, so anyone can read it. Anything that gives value must come from a machine you control, holding a server credential that never leaves your servers. That covers scores that matter, currency, server-only saves, task progress and bans.

Which credential your server uses

MultiConnectSDK finds the credential by itself. McAppServer.HasCredential is true when it found one.

Where the server runs Credential What to do
A Server deployment on MultiConnectCloud, linked to the app Provided to the container by MultiConnectCloud Nothing
An API deployment on MultiConnectCloud, chosen as the app's Backend API deployment Provided to the container by MultiConnectCloud Choose it once, as below
Anywhere else: your own machines, another cloud, your PC A server key Create one, as below

Choose the backend API deployment. On Sign-in and server access, under Game server access, pick your game's API deployment in Backend API deployment. Each API deployment can be the backend of one app.

Create a server key:

  1. On the same panel, choose Create key and name it after the server that uses it.
  2. Copy the key and its secret. The secret is shown once.
  3. On that server, set the environment variables MC_APP_SERVER_KEY and MC_APP_SERVER_SECRET to them, or call McAppServer.UseServerKey(key, secret) at startup.

An app can have up to 5 server keys. Revoke one there when it is no longer used.

Script 6.1: Use a server key from your own configuration

using System;
using MultiConnect.App;

public static class AppServerSetup
{
    public static void Configure(string key, string secret)
    {
        // On MultiConnectCloud this call is not needed: the credential is found automatically.
        if (!McAppServer.HasCredential)
            McAppServer.UseServerKey(key, secret);

        Console.WriteLine("App server credential: " + (McAppServer.HasCredential ? "found" : "missing"));
    }
}

A request made with a server key is signed over its whole body, so a captured request cannot be replayed with a different score.

McAppServer works on any thread and uses no Unity API, so it runs the same in a Unity server build, a .NET server and an ASP.NET API.

Check a player in your game API

Send the session, not the player id. When your game client calls your own API, send McApp.SessionToken with the request. A playerId sent from the client could be anyone's. A session token proves who is calling.

Script 6.2: Client side: send the session token to your API

using System.Threading.Tasks;
using MultiConnect.App;
using UnityEngine.Networking;

public static class MyGameApi
{
    public static async Task<string> Post(string url, string json)
    {
        using var request = new UnityWebRequest(url, "POST");
        request.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(json));
        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("X-Player-Session", McApp.SessionToken);

        var operation = request.SendWebRequest();
        while (!operation.isDone) await Task.Yield();
        return request.downloadHandler.text;
    }
}

Script 6.3: API side: find out who is calling

using System.Threading.Tasks;
using MultiConnect.App;

public static class PlayerCheck
{
    /// <summary>The verified player id, or "" when the session is missing, expired or banned.</summary>
    public static async Task<string> WhoIsCalling(string sessionTokenFromHeader)
    {
        var result = await McAppServer.VerifyPlayerAsync(sessionTokenFromHeader);
        return result.Ok && result.Value != null ? result.Value.playerId : "";
    }
}

Answers are cached for a minute per token, so checking on every request is cheap. For the same reason, a ban or sign-out reaches your API within a minute.

Admit only signed-in players to your game server

What this protects against: without a check, a client can connect to your game server under any player id it likes. With player sessions on, the server admits a connection only when it carries a live session of the player whose id it connects as.

Server:

  1. Turn on Require Connect Token on the server component (MultiConnectGameServer or MultiConnectMasterServer), or set RequireConnectToken in the .NET server's options.
  2. Call McAppServer.UsePlayerSessions() once at startup, before players connect.

Client:

  1. Sign in first. McApp hands the session to the connection for you.
  2. Connect with McApp.Player.playerId as the client id.

Script 6.4: Game server: check player sessions

using MultiConnect.App;
using UnityEngine;

public class PlayerSessionCheck : MonoBehaviour
{
    private void Awake()
    {
        // Runs before the server starts accepting players.
        McAppServer.UsePlayerSessions();
    }
}

Put Script 6.4 on the same object as your server component in the server scene.

Script 6.5: Client: connect as the signed-in player

using MultiConnect;
using MultiConnect.App;
using MultiConnect.Client;
using UnityEngine;

public class ConnectAsPlayer : MonoBehaviour
{
    private async void Start()
    {
        if (!McApp.IsSignedIn)
        {
            Debug.Log("Sign in first (Script 3.1).");
            return;
        }

        bool connected = await Client.ConnectToServer(ServerRegions.Any, McApp.Player!.playerId);
        Debug.Log(connected ? "Connected." : "Could not connect.");
    }
}

The Developer Guide covers connecting and the rest of the client and server components.

Other server calls about players

Call What it does
McAppServer.GetPlayerAsync(playerId) Reads a player's profile and sign-in methods
McAppServer.UpdatePlayerAsync(playerId, displayName, avatarId, email, clearEmail) Sets a player's name, avatar or (custom sign-in only) email as your game knows them. Empty values are left as they are; clearEmail: true removes the email
McAppServer.BanAsync(playerId, reason, hours) Bans a player. hours = 0 is permanent. The player sees reason
McAppServer.UnbanAsync(playerId) Lifts a ban
McAppServer.SetPlayerLevelAsync(playerId, level) Sets the player's level, which picks their reward multiplier (section 11)
McAppServer.DeletePlayerAsync(playerId) Deletes the player, as McAppAuth.DeleteAccountAsync does from the client. For games that run their own account deletion: call it as part of yours