Recently I was running some code against the Dynamics SDK that was taking a significant amount of time to run (transferring of data). In my naivety, I had thought that by constantly doing “something” on that live connection my token would be refreshed.
Not the case.
It seems tokens from the Dynamics SDK are set at the time of connection and kept for the duration of the connection and not updated until you do so again.
To avoid having my connection cut during this migration (which was bad), I added some logic to check when the connection had last logged in, do a quick comparison of X minutes (in my case I chose 90 minutes but it could be more) and triggered a reconnect/refresh of my token.
The code is nothing spectacular, but understanding the need for doing it and when to do it was the key to implementing it properly and getting past this problem.
Here is the generic error you might be receiving in this case that you can try this pattern on to resolve your issue.
System.ServiceModel.Security.MessageSecurityException: An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail. ---> System.ServiceModel.FaultException: At least one security token in the message could not be validated.