我基本上從這里獲取代碼https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-multitenant-openidconnect/blob/master/TodoListWebApp/DAL/EFADALTokenCache.cs但它不適合我應用程序,因為我不需要示例中給出的每個用戶的緩存。因此,我刪除了接受 User 作為參數的構造函數,因為我希望緩存是全局的。我想出了這個版本: public class EFTestTokenCache : TokenCache { private TestEntities _TestEntities = new TestEntities(); private TestTokenCache _cache; public EFTestTokenCache() { this.AfterAccess = AfterAccessNotification; this.BeforeAccess = BeforeAccessNotification; this.BeforeWrite = BeforeWriteNotification; } // clean up the DB public override void Clear() { base.Clear(); foreach (var cacheEntry in _TestEntities.TestTokenCaches) _TestEntities.TestTokenCaches.Remove(cacheEntry); _TestEntities.SaveChanges(); } // Notification raised before ADAL accesses the cache. // This is your chance to update the in-memory copy from the DB, if the in-memory version is stale void BeforeAccessNotification(TokenCacheNotificationArgs args) { if (_cache == null) { // first time access _cache = _TestEntities.TestTokenCaches.FirstOrDefault(c => c.webUserUniqueId == args.DisplayableId); } else { // retrieve last write from the DB var status = from e in _TestEntities.TestTokenCaches where (e.webUserUniqueId == args.DisplayableId) select new { LastWrite = e.LastWrite };您認為這作為全局緩存是否可以正常工作,還是有問題并且始終必須像示例中給出的那樣基于用戶?另一個查詢是為什么數據庫在Clear(). 這是否意味著每當應用程序池關閉或我的數據庫將被清除?但這不應該發生。任何幫助表示贊賞。
1 回答
開心每一天1111
TA貢獻1836條經驗 獲得超13個贊
如果您嘗試實現全局令牌緩存而不考慮用戶,那么我會看到您的代碼存在問題,因為代碼正在尋找每個登錄用戶的任何現有緩存,因為代碼正在使用 webUserUniqueId 進行過濾
_TestEntities.TestTokenCaches.FirstOrDefault(c => c.webUserUniqueId == args.DisplayableId);
在正確的示例代碼中,每個用戶都有一組保存在數據庫中(或作為集合)的令牌,因此當他們登錄到 Web 應用程序時,他們可以直接執行 Web API 調用,而無需重新進行身份驗證/重復同意。
我不確定您為什么要這樣做,但在我看來,如果您要為 Web 實現自定義令牌緩存,最好為不同的登錄用戶提供所需的令牌之間的隔離級別。
此外,Clear() 方法通過刪除 db 中的所有項目來清除緩存,但在 GitHub 示例中尚未調用此方法,您需要從 AccountController 的 SignOut() 方法中添加對 authContext.TokenCache.clear() 的調用以在用戶注銷時清除緩存。
- 1 回答
- 0 關注
- 251 瀏覽
添加回答
舉報
0/150
提交
取消
