atlas by clearpeople

Azure Active Directory TokenCache based on Entity Framework DB (issue in MS code)

30 June 2017
  

If you’re working with secure web applications with Azure Active Directory, you’re probably working with ADAL. ADAL has its own Token Cache (wonderfully explained in this post from the father of ADAL, Vittorio Bertocci. The Token Cache included in ADAL, it’s only suitable for native applications because it works “in memory”, so this will be a problem sooner or later for web applications. Fortunately, with ADAL v2, we can implement our own token cache, just inheriting from the TokenCache class. In fact, there’re a couple of examples in the same post of Vittorio, and one of them is based on SQL Server with Entity Framework. Therefore, it can be used perfectly for web applications.

 

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” 

 

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!

Author bio

Luis Mañez

Luis Mañez

Luis is Atlas Chief Architect. He is also a Microsoft 365 Development MVP and SharePoint and Cloud Solutions architect. "I help find the best technical designs to meet client needs and act as tech lead to build great solutions. I have fun with some R&D tasks, always trying to improve our tools and processes, and I often help the Microsoft community as a blogger and speaker, contributing to open-source projects."

View all articles by this author View all articles by this author

Get our latest posts in your inbox