IIS で .NET Core Webアプリケーションを実行すると、時々 "DefaultAntiforgery" の "The antiforgery token could not be decrypted." エラーが発生する - IIS

IIS で .NET Core Webアプリケーションを実行すると、時々 "DefaultAntiforgery" の "An exception was thrown while deserializong the token." "The antiforgery token could not be decrypted." エラーが発生する現象についてです。

現象

ASP.NET CoreアプリケーションでフォームのPOSTを実行した際に、アプリケーションの処理が実行できず、HTTPエラー 500が発生します。

IIS で ASP.NET Core アプリケーションを実行していると、時々下記のエラーが発生します。
"The antiforgery token could not be decrypted." がエラーの内容になります。
Category: Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery
EventId: 7
RequestId: 8000084c-0002-ba00-b63f-84710c7967bb
RequestPath: (アプリケーションのURL)
SpanId: |cd9a1145-4788669cede37db7.
TraceId: cd9a1145-4788669cede37db7
ParentId: 
ActionId: 10376a35-66ea-4be9-b503-5737eab54122
ActionName: (アプリケーションのアクション)

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 {5ea39406-46e1-46c3-b368-e049d9d02ca3} 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)


発生条件

詳しい発生条件は不明ですが、フォーム画面を表示後、長い時間そのままにした後でPOSTを実行するとエラーが発生する確率が高いです。

対処方法

下記の設定変更でエラーの発生を大幅に減らせます。

[インターネット インフォメーション サービス(IIS) マネージャー]を起動します。下図のウィンドウが表示されます。
左側のツリービューのサーバーのノードの子ノードの[アプリケーション プール]のノードをクリックして選択します。右側にアプリケーションプールの一覧が表示されます。 エラーが発生するASP.NET Coreアプリケーションを実行しているアプリケーションプールの項目をクリックして選択し、右クリックします。ポップアップメニューが表示されますので [詳細設定]の項目をクリックします。


[詳細設定]ダイアログが表示されます。


ダイアログの項目中の [ユーザープロファイルの読み込み] の設定を確認します。デフォルトでは "False"になっています。


値のエリアをクリックします。ドロップダウンリストが表示されますので "True" をクリックして選択します。


値を "True" に設定しました。設定後ダイアログの[OK]ボタンをクリックしてダイアログを閉じます。


設定後、ASP.NET Core アプリケーションを実行して現象が改善されたかを確認します。

補足:さらにエラーを減らしたい場合

上記の設定で、"The antiforgery token could not be decrypted." のエラーは大幅に減少しますが、完全には解消されない場合があります。完全に解消されない場合は「クロスサイト要求偽造(antiforgery )」を無効にする対処法も有効です。クロスサイト要求偽造を無効にする手順はこちらの記事を参照して下さい。

著者
iPentec.com の代表。ハードウェア、サーバー投資、管理などを担当。
Office 365やデータベースの記事なども担当。
最終更新日: 2021-10-30
作成日: 2020-03-16
iPentec all rights reserverd.