How to refresh an Access Token when it expires? (= after 2 hours) using the C# SDK and the Refresh token on the game client?

I’m having trouble redeeming entitlements when my access token expires, and even re-logging in by calling the connectInterface.Login() when the notification callback of `AddNotifyAuthExpiration()` triggers, doesn’t make the AccessToken “expiration timer” reset.

Logging in again to the Connect interface with the just-obtained AccessToken

(from `platformInterface.GetAuthInterface().CopyUserAuthToken(ref copyUserAuthTokenOptions, localUserId, out token);` ) does not reset the AccessToken’s expiration timer, so after the 2nd refresh the token expires anyway, making the last token be valid only for a few minutes.

When another hour passes, the token refreshes again and everything goes well, so there are these awkward ~45/50 minutes in which the AccessToken is unusuable.

What happens in cronological order:

  1. [time: 00:00] Player logs in: gets access token and refresh token
  2. A callback is added to AddNotifyAuthExpiration
  3. [time: 00:50] ~50 minutes elapse, the callback is called, I invoke connectInterface.Login() -> the Access token is still valid, so I get it again
  4. [time: 01:40] other ~50 minutes elapse, the callback is called, I invoke connectInterface.Login() -> the Access token is still valid, so I get it again
  5. [time: 02:00] ~20 minutes elapse -> the Access token EXPIRES as per documentation
  6. [time: 02:30] ~30 minutes elapse the callback is called, I invoke connectInterface.Login() -> the Access token is now usable again

How do we make sure the Access token properly resets when we call connect? The documentation heresays “The game must periodically refresh the player’s token based on expiration notification events”.

But that’s what I’m doing, and it’s not working.

And here it says The game client will need to use the refresh token if the access token expires , but I couldn’t find any API to do that. How are we supposed to do it?

SDK version: 1.16.4

OS: Windows

Engine: Unity (C# SDK)

Platform: ticking every Update()

The Epic Account Services token is automatically refreshed by the SDK. The documentation you linked is for the Auth Web API. Are you calling Auth.CopyIdToken and then calling Connect.Login with the EOS_ECT_EPIC_ID_TOKEN every hour, after the Connect.AddNotifyAuthExpiration callback function has fired? That’s all that you should need to do for the player to remain logged in.

Thanks for sharing all of this information. As you are using the token on behalf of the user on your backend, you do need to use the user auth token returned from EOS_Auth_CopyUserAuthToken. The ID token returned from EOS_Auth_CopyIdToken can be used to authenticate a user, but not perform actions on their behalf (like enumerating their entitlements). Sorry for the confusion here, I had assumed you were initially talking about your game client.

EOS_Auth_CopyUserAuthToken should be giving you an updated auth token when it is called. Are you seeing that calling this function after 2 hours returns an expired token? If you’re caching the first token that is returned and trying to use it after 2 hours, that’s the issue. Alternatively, with our Auth Web API, you could use the refresh_token grant type and pass in the refresh token to extend the the time the token is valid for. See the docs here: https://dev.epicgames.com/docs/web-api-ref/authentication\#authentication

I forgot to answer that part of your question. At the moment, there is no way to force the expiration to happen sooner. We have this (and expiring the Connect token sooner) in our feature request backlog. Let me know if the issue persists.

It’s finally fixed. The main issues were 2, and I had to solve both of them:

  1. The token I was sending around through the LoginOptions was the old one. I fixed this by adding a public instance of LoginOptions to my EOS Manager singleton, and updating it with the new Access token I get from CopyUserAuthToken (which you MUST call when the old token expires)
  2. Calling connect in the AuthExpirationCallback is a mistake. The right place to do it is in the LoginStatusChangedCallback:
void AuthExpirationCallback(ref AuthExpirationCallbackInfo data)
{
    // This is called 10-minutes before the token expires. Don't do Connect.Login() here or you'll start getting errors after the 2nd refresh!
   /Debug.Log($"(UTC: {DateTime.UtcNow}) Player will soon be logged out, attempting re-connection");
}

void LoginStatusChangedCallback(ref Connect.LoginStatusChangedCallbackInfo data)
{
    Debug.Log($"(UTC: {DateTime.UtcNow}) LoginStatusChangedCallback status: {data.CurrentStatus}");
    switch (data.CurrentStatus)
    {
        case LoginStatus.NotLoggedIn:
            if (data.PreviousStatus == LoginStatus.LoggedIn)
            {
                // Handle token expiration
                Debug.Log($"(UTC: {DateTime.UtcNow}) Player was logged out, attempting re-connection");
                ReconnectToConnectInterface();
            }
            break;
        case LoginStatus.UsingLocalProfile:
            break;
        case LoginStatus.LoggedIn:
            break;
    }
}

you need to subscribe to those only ONCE the first time you successfully log in / create an account:

ConnectInterface connectInterface = GetEOSPlatformInterface().GetConnectInterface();
connectInterface.Login(ref options, null, (ref Connect.LoginCallbackInfo data) =>
{
    if (data.ResultCode == Result.Success) //successfully logged in
    {
        ConfigureConnectExpirationCallback(); //this is the right place!
    }
});

bool alreadyRegistered = false;
void ConfigureConnectExpirationCallback()
{
    if (alreadyRegistered)
    {
        return;
    }
    var EOSConnectInterface = GetEOSConnectInterface();
    var addNotifyAuthExpirationOptions = new AddNotifyAuthExpirationOptions();
     EOSConnectInterface.AddNotifyAuthExpiration(ref addNotifyAuthExpirationOptions, LoginOptions, AuthExpirationCallback);

    var notifyLoginStatusChangedOptions = new Connect.AddNotifyLoginStatusChangedOptions();
    EOSConnectInterface.AddNotifyLoginStatusChanged(ref notifyLoginStatusChangedOptions, LoginOptions, LoginStatusChangedCallback);
}

That’s it!

Hey Seb, thanks for the answer.

After further testing I discovered that both the AccessToken effectively change after the 2 hours mark, however calling connectInterface.Login() at that point makes the LoginCallback return a ConnectExternalTokenValidationFailed status code/error, meaning that something goes wrong and effectively “preventing” the login.

Failed to login user to services. ConnectExternalTokenValidationFailed
UnityEngine.Debug:ExtractStackTraceNoAlloc (byte*,int,string)
UnityEngine.StackTraceUtility:ExtractStackTrace ()
UnityEngine.DebugLogHandler:Internal_Log (UnityEngine.LogType,UnityEngine.LogOption,string,UnityEngine.Object)
UnityEngine.DebugLogHandler:LogFormat (UnityEngine.LogType,UnityEngine.Object,string,object[])
UnityEngine.Logger:Log (UnityEngine.LogType,object)
UnityEngine.Debug:LogError (object)
Epic.OnlineServices.Platform.EOSSDKComponent/<>c__DisplayClass80_0:<StartConnectLoginWithOptions>b__0 (Epic.OnlineServices.Connect.LoginCallbackInfo&) (at Assets/AutoVine/Scripts/TCG/Application/Runtime/Components/EOSSDKComponent.cs:798)
Epic.OnlineServices.Connect.ConnectInterface:OnLoginCallbackInternalImplementation (Epic.OnlineServices.Connect.LoginCallbackInfoInternal&) (at ./Library/PackageCache/com.aheadgames.eos/Runtime/Source/Generated/Connect/ConnectInterface.cs:958)
Epic.OnlineServices.Platform.PlatformInterface:Tick () (at ./Library/PackageCache/com.aheadgames.eos/Runtime/Source/Generated/Platform/PlatformInterface.cs:944)
Epic.OnlineServices.Platform.EOSSDKComponent:Update () (at Assets/AutoVine/Scripts/TCG/Application/Runtime/Components/EOSSDKComponent.cs:1021)

Here’s a few more info that could help us troubleshoot:

  1. A bit more context: I need to be able to enumerate entitlements from an authoritative source (not the game client). I have a cloud function that does this, and I need to send it a valid access token. Right now the problem is that after the 2 hours mark, the token I send is not recognized as “valid”. Everythign works fine before the 2-hours mark.
  2. In my LoginOptions, I’m using ExternalCredentialType.Epic (not EpicIdToken), and I pass UserAuthToken.Value.AccessToken (which is obtained through authInterface’s CopyUserAuthToken)
  3. I’m not using EpicIdToken because the JWT token I get by authInterface.CopyIdToken doesn’t seem valid for the entitlements WEB API (I don’t get any entitlement for the user when I send the JWT token obtained in the ExternalCredentialType.EpicIdToken workflow, but I get them when I send the AccessToken obtained in the ExternalCredentialType.Epic workflow).

Side question is there a way to force the token to expire before 2 hours, so I can iterate faster on this bug? It’s a pain to wait 2.5 hours every time I want to test a potential fix.

if it can help further, this is what I get when I try to use the JWT token, obtained in the ExternalCredentialType.EpicIdToken workflow, on the web api to check the unredeemed entitlements of a player:

"errorCode":"errors.com.epicgames.common.authentication.token_verification_failed","errorMessage":"Sorry we couldn't validate your token. Please try with a new token.","messageVars":[],"numericErrorCode":1031,"originatingService":"com.epicgames.ecommerce.integration.public","intent":"prod"}"

And this is the code that calls the entitlements API, just in case there’s something wrong there:

//in an ASP.NET function

using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"https://api.epicgames.dev/epic/ecom/v3/identities/{userEpicID}/entitlements?sandboxId={sandboxId}"))
{
  requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

  var httpClient = new HttpClient();
  var response = await httpClient.SendAsync(requestMessage);
  var jsonString = await response.Content.ReadAsStringAsync();
   //jsonString is the error above
}

Side note: the player is successfully logged in in game, and can access other information (I.E: its own stats). It’s only the entitelements API that doesn’t like the JWT token.

> Are you seeing that calling this function after 2 hours returns an expired token?

No, I see a different token that expires 2 hours later (according to its ExpiresAt property).

And when I get that token, I

  1. Update the cache
  2. Re-attempt connect.login()

However, while writing this answer I realized that maybe I’m sending the old login options around, which might have the expired token. I’ll start a new test run now, will be able to tell you if we finally fixed this in ~3 hours!

Got it, thanks.

Unfortunately I think I messed up the implementation of the fix I wasn’t getting a new token anymore, I’ll let you know what happens in a couple hours.

As an experimento, I’m now trying to refresh the token directly when the callback for `AddNotifyLoginStatusChanged` triggers (instead of using the one from AddNotifyAuthExpiration ), so that I can refresh the token right when it expires.

Is that a good/bad approach, in your opinion?