Unity AuthenticateCustomAsync Error

I am setting up a Nakama connection in Unity.
When I do AuthenticateDeviceAsync it works but when I try to use AuthenticateCustomAsync I get the error “Authentication failed: Exceeded max retry attempts.”.
When I use this same function in UE5 it works so idk what the problem is

using UnityEngine;
using Nakama;
using System.Threading.Tasks;

public class NakamaService
: MonoBehaviour
{
[SerializeField] private NakamaConfig nakamaConfig;

public static IClient Client;
public static ISession Session;
public static ISocket Socket;


private async void Start()
{
    Debug.Log("Initializing Nakama...");

    string scheme = nakamaConfig.UseSSL ? "https" : "http";
    Client = new Client(
        scheme,
        nakamaConfig.Host,
        nakamaConfig.Port,
        nakamaConfig.ServerKey
    );

    Client.Timeout = nakamaConfig.Timeout;
    Client.Logger = new UnityLogger();
    

    try
    { 
        Session = await AuthenticateCustomAsync();
    }
    catch (System.TimeoutException)
    {
        Debug.LogError("Connection timed out. Could not authenticate.");
    }
    catch (System.Exception ex)
    {
        Debug.LogError($"An error occurred: {ex.Message}");
    }
    
    await InitializeSocket();
}

private async Task<ISession> AuthenticateCustomAsync()
{
    string customId = System.Guid.NewGuid().ToString(); // Generate unique ID
    Client.Logger.InfoFormat("Authenticating with custom ID: {0}", customId);
    try
    {
        ISession session = await Client.AuthenticateCustomAsync(customId);
        Debug.Log($"Authenticated with Nakama! User ID: {session.UserId}");
        return session;
    }
    catch (System.Exception ex)
    {
        Debug.LogError($"Authentication failed: {ex.Message}");
        throw;
    }
}

 private async Task InitializeSocket()
{
    Socket = Client.NewSocket();

    Socket.Connected += () => Debug.Log("Socket connected!");
    Socket.Closed += () => Debug.Log("Socket disconnected!");

    try
    {
        await Socket.ConnectAsync(Session, true);
        Debug.Log("Socket connection successful!");
    }
    catch (System.Exception ex)
    {
        Debug.LogError($"Failed to connect socket: {ex.Message}");
    }
}

}

Hello @Doglightning,

Are there no server logs that may indicate the issue?

Best.

Here is my log for AuthenticateDeviceAsync

2024-12-11 11:33:08 {“level”:“info”,“ts”:“2024-12-11T16:33:08.508Z”,“caller”:“server/session_ws.go:81”,“msg”:“New WebSocket session connected”,“uid”:“4a3686ba-ddc5-461f-82ff-7b67b5a1f97a”,“sid”:“9ad50ac0-b7dd-11ef-9a26-006100a0eb06”,“format”:0}
2024-12-11 11:34:13 {“level”:“info”,“ts”:“2024-12-11T16:34:13.454Z”,“caller”:“server/session_ws.go:520”,“msg”:“Closed client connection”,“uid”:“4a3686ba-ddc5-461f-82ff-7b67b5a1f97a”,“sid”:“9ad50ac0-b7dd-11ef-9a26-006100a0eb06”}

There are no logs for AuthenticateCustomAsync

I think the client logs what’s causing the requests to retry and cause the failure, can you paste them here please?

Here is the log for the POST

Send: method=‘POST’, uri=‘http://localhost:7350/v2/account/authenticate/custom?create=true&’, body=‘System.Byte
UnityEngine.Debug:LogFormat (string,object)
Nakama.UnityLogger:InfoFormat (string,object) (at Assets/Packages/Nakama/Runtime/UnityLogger.cs:31)
Nakama.HttpRequestAdapter/d__8:MoveNext ()
System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<string>:Start<Nakama.HttpRequestAdapter/<SendAsync>d__8> (Nakama.HttpRequestAdapter/<SendAsync>d__8&) Nakama.HttpRequestAdapter:SendAsync (string,System.Uri,System.Collections.Generic.IDictionary2<string, string>,byte,int,System.Nullable1<System.Threading.CancellationToken>) Nakama.ApiClient/<AuthenticateCustomAsync>d__12:MoveNext () System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<Nakama.IApiSession>:Start<Nakama.ApiClient/d__12> (Nakama.ApiClient/d__12&)
Nakama.ApiClient:AuthenticateCustomAsync (string,string,Nakama.ApiAccountCustom,System.Nullable1<bool>,string,System.Nullable1<System.Threading.CancellationToken>)
Nakama.Client/<>c__DisplayClass45_0:b__0 ()
Nakama.RetryInvoker/d__21<Nakama.IApiSession>:MoveNext () System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<Nakama.IApiSession>:Start<Nakama.RetryInvoker/d__21<Nakama.IApiSession>> (Nakama.RetryInvoker/<InvokeWithRetry>d__21<Nakama.IApiSession>&)
Nakama.RetryInvoker:InvokeWithRetry<Nakama.IApiSession> (System.Func1<System.Threading.Tasks.Task1<Nakama.IApiSession>>,Nakama.RetryHistory)
Nakama.Client/d__45:MoveNext ()
System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<Nakama.ISession>:Start<Nakama.Client/<AuthenticateCustomAsync>d__45> (Nakama.Client/<AuthenticateCustomAsync>d__45&) Nakama.Client:AuthenticateCustomAsync (string,string,bool,System.Collections.Generic.Dictionary2<string, string>,Nakama.RetryConfiguration,System.Threading.CancellationToken)
NakamaService/d__18:MoveNext () (at Assets/Scripts/NakamaService/NakamaService.cs:65)
System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1<Nakama.ISession>:Start<NakamaService/d__18> (NakamaService/d__18&)
NakamaService:AuthenticateDeviceAsync ()
NakamaService/d__17:MoveNext () (at Assets/Scripts/NakamaService/NakamaService.cs:33)
System.Runtime.CompilerServices.AsyncVoidMethodBuilder:Start<NakamaService/d__17> (NakamaService/d__17&)
NakamaService:Start ()

Here is the retry error
Authentication failed: Exceeded max retry attempts.
UnityEngine.Debug:LogError (object)
NakamaService/d__18:MoveNext () (at Assets/Scripts/NakamaService/NakamaService.cs:71)
System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<Nakama.ISession>:SetException (System.Exception) Nakama.Client/<AuthenticateCustomAsync>d__45:MoveNext () System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<Nakama.IApiSession>:SetException (System.Exception)
Nakama.RetryInvoker/d__21<Nakama.IApiSession>:MoveNext () System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<Nakama.IApiSession>:SetException (System.Exception)
Nakama.RetryInvoker/d__21<Nakama.IApiSession>:MoveNext () System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<Nakama.IApiSession>:SetException (System.Exception)
Nakama.RetryInvoker/d__21<Nakama.IApiSession>:MoveNext () System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<Nakama.IApiSession>:SetException (System.Exception)
Nakama.RetryInvoker/d__21<Nakama.IApiSession>:MoveNext () System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<Nakama.IApiSession>:SetException (System.Exception)
Nakama.RetryInvoker/d__21<Nakama.IApiSession>:MoveNext () System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<Nakama.IApiSession>:SetException (System.Exception)
Nakama.ApiClient/d__12:MoveNext ()
System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1:SetException (System.Exception)
Nakama.HttpRequestAdapter/d__8:MoveNext ()
UnityEngine.UnitySynchronizationContext:ExecuteTasks ()

Are you sure that the config values that are passed to the client constructor are correct?

Yes, It works with Client.AuthenticateDeviceAsync(deviceId) using the exact same Client that fails with AuthenticateCustomAsync

What versions of the client and server are you using? Do you have any custom hooks in place on AuthenticateCustom ?

Client: 3.12.0
Server: 3.22.0
No custom hooks

Have you tried invoking the REST API directly using cURL?

I am not 100% sure how to do the API call as it says my key is invalid but this is the key used on my unity project that works

image

For authentication APIs you must set the request auth to Basic with username defaultkey and the body should be something like:

{"id": "some-custom-id"}