排除 .NET Core CryptographicException 問題

因想防止 xsrf 攻擊

所以使用了 Microsoft.AspNetCore.Antiforgery 來產 token

在本機都正常執行

但發佈到 IIS 後,卻發現無法正常存取 API

查看事件檢視器看到以下錯誤:

Category: Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery
EventId: 7
RequestId: 800000f2-0001-f900-b63f-84710c7967bb
RequestPath: /api/security/xsrf-token
SpanId: |f710ac30-480cf8c450886f7b.
TraceId: f710ac30-480cf8c450886f7b
ParentId:
ActionId: 8ba194b3-e8d8-40a7-a818-faee4e5bb185
ActionName: Controllers.SecurityController.GetXsrfToken
An exception was thrown while deserializing the token.

Exception:
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted.
 ---> System.Security.Cryptography.CryptographicException: The key {a49f3135-4726-40b4-bab4-63ae47e90b4a} was not found in the key ring.
   at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
   at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
   at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
   at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
   --- End of inner exception stack trace ---
   at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
   at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.GetCookieTokenDoesNotThrow(HttpContext httpContext)




開啟 IIS 的應用程式集區

選擇所使用的應用程式,按右邊的進階設定


在處理序模型下,將載入使用者設定檔,改成 True (預設是 false)

可參考這篇文章 提到的 setProfileEnvironment attribute 設定


然後再重新啟用看看

我這邊是將 IIS、應用程式還有網站都重啟,都還是出現錯誤訊息

最後是重新開機才終於排除問題

留言

這個網誌中的熱門文章

CPE 一顆星選集題目說明與解答 - Java 筆記與心得分享

Visual Studio 自動排版格式化程式碼

1. Vito's family (CPE10406, UVA10041) - CPE一顆星解答與說明