We’re setting up Nakama for our game and I wonder what the best practice is when it comes to handling expired sessions.
Any time we need a valid session there’s a risk the session is expired, so would it make sense to
A) Have a helper function ex. getValidSession() that checks if it’s valid, and if not re-authenticates with Nakama?
B) Catch the Unauthorized exception and only then re-authenticates
Initially A seems to be the way to go? Or maybe there’s some third option, having some background task that knows when it expires that will re-authenticate?
Also, while on the topic, there’s this sample code that was on github:
var expiredDate = System.DateTime.UtcNow.AddDays(-1);
if (session == null || session.HasExpired(expiredDate)) { ... }
I don’t understand the expiredDate check? It sets a date/timestamp that’s a day in the past and checks if it has expired with that as a parameter? Why not just session.IsExpired? What does HasExpired do differently?
And lastly, all links here are broken (on the page not the sidebar): Session - Nakama server
@nixarn My recommendations on how best to handle the session lifecycle is these simple rules:
I would set the session token lifetime to be 7 days or similar. This is a practical balance between authentication, authorization, and convenience for the end user. (See the session.token_expiry_sec option in the server.)
I would incorporate social sign-in into the game as early as possible. With mobile this could be Apple Game Center, Google Play Games, Apple Sign-In, Facebook, Facebook Limited Login, etc. This eliminates most of the hassle with re-authentication by the user because all of those social providers have a silent sign-in option once the first authentication has been done.
Make a check at game start whether the session token is within 24 hours of its expiration and re-authenticate the user. This way you can extend the lifetime of the session without an interruption to the user’s play experience that day.
You can also use device ID authentication by default to avoid the need for social sign-in with the initial play experience.
Also, keep an eye on the latest work in the Nakama Unity client where we’re about to open a pull request for review that uses the refresh tokens work added in Nakama 3.0 server. This will let you refresh a session on demand as well as enable auto-refresh a session.
This will not totally eliminate the need to re-authenticate the user because refresh tokens have their own lifetime and can expire (though this can also be configured). (See the session.refresh_token_expiry_sec option in the server.)