Restoring a Session

I’m using the Unity client SDK and whenever the app goes into the background, I save the authToken and refreshToken to player prefs. Then if my iOS app is forced closed and opened again, I try to restore the session using the following:

Session.Restore(authToken, refreshToken)

However, I’ve found that if I restart the Nakama server before I force close the iOS app, this Session.Restore will appear to succeed but the player isn’t actually authenticated. Is there a simple way to detect if the session is valid or not or should I set up a simple RPC function that the client can try to ping to see if it gets a response from the server ?

Hello @Spuddy,

The sessions will be invalidated on the server upon server restart, the Restore function simply returns a new ISession object with authToken and refreshToken, if it has been invalidated on the server it’ll appear to be valid but the server will reject it.

Usually the client should always look out for 404 exceptions and prompt reauthentication is such cases, but if you need to check explicitely, setting up a dedicated RPC as you suggest is a good option.

Hope this helps

Right now, the way I check if the session is valid after calling Session.Restore(…) is by trying to connect the socket in a try/catch statement:

try {
  await mysocket.ConnectAsync(mysession, true, 5);   // time out after 5 seconds
  // success so assume authenticated
}
catch {
  // failed so need to authenticate
}

I’m not sure how reliable this technique is so I’ll probably change it to the RPC ping route but does the ConnectAsync throw an exception and hit the catch statement if the tokens are invalid and also does it execute the catch statement if it times out after 5 seconds too ? If it does then it’s probably a valid method but I feel RPC would be more reliable ?