Skip to content

7. Use EF Core interceptors to hook AAD authentication with tokens

Compare
Choose a tag to compare
@mderriey mderriey released this 20 Feb 03:13
9f8e910

The method we found to hook into the SqlConnection lifetime with EF Core is to use interceptors: https://docs.microsoft.com/ef/core/logging-events-diagnostics/interceptors.

In this case, we use a connection interceptor and inspect it just before EF Core opens it.
We need to override both the synchronous and asynchronous methods of the interceptor because EF Core will call one or the other depending on how we interact with your EF Core context:

  • If we use .ToList(), .ToArray(), .Any(), the synchronous OnConnectionOpening method will be called on the interceptor.
  • If we use .ToListAsync(), .CountAsync(), .ToDictionaryAsync(), the asynchronous OnConnectionOpeningAsync one will be invoked.

This means we have to add support for synchronous operations to our token acquisition process.
Luckily for us, Azure Identity and the in-memory cache support it, so it's a matter of adding another method.

Diff from previous tag: 6.ef-core-basic-implementation...7.leverage-interceptors-to-use-aad-auth-with-tokens