This same code of TokenCache based on DB is in several examples in the GitHub of Azure AD, like this one, as well as in a bunch of articles, “around the web”.
Well, I’m far from being an expert on Entity Framework, but given the tests that I have made with my limited knowledge about EF, that code has an issue that can cause problems in some scenarios. The problem is in the next method fragment “AfterAccessNotification”
As you can see, if a new object is being created all the time “PerWebUserCache”, a new item will be always added in the Table, and it will never update the existing one. This can cause us issues later, when the cache is checked and the token is returned for the user, because it can return a Token already expired.
I’m not the first one detecting the issue, since there’s already an existing issue in GitHub , but MS hasn’t fixed it yet
I have created a Pull Request trying to fix the issue, and it’s waiting for approval. For now, I leave you here the complete class code.
As you can see, the fix consists on checking if we already have the DB record loaded and if that’s the case, we update the serialized Token, and the last write date. If not, then we create a new record.
I hope this helps, and if you’re experts in EF and you have a better way of fixing it, leave a comment, please!