7. Use EF Core interceptors to hook AAD authentication with tokens
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 synchronousOnConnectionOpening
method will be called on the interceptor. - If we use
.ToListAsync()
,.CountAsync()
,.ToDictionaryAsync()
, the asynchronousOnConnectionOpeningAsync
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