我能夠複製這幾乎完全。在IDE調試器下運行,它可以很好地工作,但如果它沒有連接到調試器,或者作爲發佈版本運行,它將默默無法存儲該令牌,並且嘗試持久性後的所有其他操作通常也無法運行。
我設法通過實現我自己的緩存來源於TokenCache
並查看它試圖做什麼來解決Android上的這個相同問題。
我所在的例子爲一個桌面應用程序,如下所述:
https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-native-dotnet
,然後看了一下他們的FileCache
因爲它是在他們的GitHub庫定義:
https://github.com/AzureADQuickStarts/B2C-NativeClient-DotNet/blob/complete/TaskClient/FileCache.cs
我複製了他們的FileCache
,並將其添加到PublicClientApplication
初始化:
ClientApplication = new PublicClientApplication(SharedConstants.AuthContext, SharedConstants.ClientId)
{
RedirectUri = "urn:ietf:wg:oauth:2.0:oob",
UserTokenCache = new FileCache(),
};
(默認情況下,大多數示例將UserTokenCache
屬性保留爲空,以推測使用平臺默認共享首選項)。
然後扭捏它做一些詳細的日誌記錄在讀/寫/只訪問,看看它是什麼達:
private void AfterAccessNotification(TokenCacheNotificationArgs args)
{
// if the access operation resulted in a cache update
try
{
this.Log().Debug("About to update token cache (if it's changed)...");
if (this.HasStateChanged)
{
this.Log().Debug("State has changed, updating cache file...");
lock (FileLock)
{
// reflect changes in the persistent store
_file.WriteAllBytes(CacheFilePath, this.Serialize());
// once the write operation took place, restore the HasStateChanged bit to false
this.HasStateChanged = false;
}
this.Log().Debug("Token cache file updated");
}
this.Log().Debug("Finished updating token cache file");
}
catch (Exception ex)
{
this.Log().ErrorException($"Something went wrong during token AfterAccessNotification: {ex.Message}", ex);
}
}
的記錄顯示,在Android上,它被扔涉及有異常不是一個DateTimeOffset
類型屬性的序列化處理程序,它位於MSAL庫的深處。
一旦我將AfterAccessNotification
封裝在try-catch中並使用處理程序記錄發生了異常,它就完全開始工作。
我一直堅持使用這個版本的FileCache
現在,因爲它大多解決了我目前的問題,但它確實意味着認證令牌等現在不能安全存儲。
我懷疑同樣的問題發生在模擬器上的iOS 10.x上,但我還沒有能夠驗證這一點。
我希望這可以幫助別人。
編輯:作爲@Henrik在他的評論中提到:編輯項目屬性,並告訴它不到Android上System.Runtime.Serialization.dll
鏈接,然後永久解決該問題。根據我的(公認的)有限的測試,可以安全地從使用FileCache
再次轉換爲默認行爲。
我已經做了一篇關於我在這裏弄清楚這個問題的博客文章:http://blog.wislon.io/posts/2016/12/05/msal-token-not-stored-on- android - 稍微不太詳細的版本作爲下面的潛在答案提供。 – wislon