Autodesk APS (Formerly Forge) – 2 legged token expires and async function does not refresh it

Error calling PostStorage: { “developerMessage”:”Access token provided is invalid or expired.”, “moreInfo”: “https://forge.autodesk.com/en/docs/oauth/v2/developers_guide/error_handling/”, “errorCode”: “AUTH-006”}’

I am having issue trying to get a new token when it expires while running a batch process. I need to restart the process manually every hour after it crashes because the token has expired.

I am using .Net and I got online this chunk of code:

        /// 
        /// The GetInternalAsync.
        /// 
        /// The .
        public async Task GetInternalAsync()
        {
            if (InternalToken == null || InternalToken.ExpiresAt < DateTime.UtcNow.AddSeconds(-1000))
            {
                InternalToken = await Get2LeggedTokenAsync(new Scope[] { Scope.BucketCreate, Scope.BucketRead, Scope.BucketDelete, Scope.DataRead, Scope.DataWrite, Scope.DataCreate, Scope.CodeAll });
                InternalToken.ExpiresAt = DateTime.UtcNow.AddSeconds(InternalToken.expires_in);
            }

            return InternalToken;
        }

        /// 
        /// Get the access token from Autodesk.
        /// 
        /// The scopes.
        /// The .
        public async Task Get2LeggedTokenAsync(Scope[] scopes)
        {
            TwoLeggedApi oauth = new TwoLeggedApi();
            string grantType = "client_credentials";
            dynamic bearer = await oauth.AuthenticateAsync(config.ClientId,
              config.ClientSecret,
              grantType,
              scopes);
            return bearer;
        }

In the app I am calling this method:

dynamic oauth = await GetInternalAsync();

I tried placing the method several times in different places on the app.
oauth = await GetInternalAsync();

I tried to call it directly without the await method and I run into a problem with type conversion of JsonResponse and Task.

I tried to reduce the time of the ExpiresAt to try to refresh it earlier.

Read more here: Source link