2016-01-07 18 views
16

以下のエラーが表示されます。これは、ビジュアルスタジオ2015を最初のアップデートにアップグレードした後に始まったようです。私はここでマシンキーの問題であることについていくつかのスレッドを読んだことがありますか?私はどのようにそれを修正し、それを防止するか分からない。現在私はIIS Expressを使用してデバッグでこれを実行すると、ローカルマシンでこのエラーが発生します。ここでデバッグ中に暗号操作中にエラーが発生しました

Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId); 

// place the entry in memory 
this.Deserialize((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits,"ADALCache")); 


[CryptographicException: Error occurred during a cryptographic operation.] 
    System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.HomogenizeErrors(Func`2 func, Byte[] input) +115 
    System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.Unprotect(Byte[] protectedData) +70 
    System.Web.Security.MachineKey.Unprotect(ICryptoServiceProvider cryptoServiceProvider, Byte[] protectedData, String[] purposes) +62 
    System.Web.Security.MachineKey.Unprotect(Byte[] protectedData, String[] purposes) +121 
    LEDES.Models.ADALTokenCache..ctor(String signedInUserId) in C:\Users\RLewis\Source\Workspaces\Workspace\LEDES\LEDES\Models\AdalTokenCache.cs:28 
    LEDES.Startup.<ConfigureAuth>b__7_0(AuthorizationCodeReceivedNotification context) in C:\Users\RLewis\Source\Workspaces\Workspace\LEDES\LEDES\App_Start\Startup.Auth.cs:54 
    Microsoft.Owin.Security.OpenIdConnect.<AuthenticateCoreAsync>d__1a.MoveNext() +4388 
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +26 
    Microsoft.Owin.Security.OpenIdConnect.<AuthenticateCoreAsync>d__1a.MoveNext() +5776 
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92 
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 
    System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28 
    Microsoft.Owin.Security.Infrastructure.<BaseInitializeAsync>d__0.MoveNext() +471 
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92 
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 
    System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 
    Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +218 
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92 
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 
    System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 
    Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +170 
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92 
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 
    System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 
    Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +525 
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92 
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 
    System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 
    Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +170 
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92 
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 
    System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 
    Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<DoFinalWork>d__2.MoveNext() +166 
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +26 
    Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow() +26 
    Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +81 
    Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +30 
    System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +380 
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 

Exception Details: System.Security.Cryptography.CryptographicException: Error occurred during a cryptographic operation.

は、それが失敗しているからであるコード - プロジェクトを設定するとき、私はAzureの認証を選択したときにこれがVSによって生成されました。

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Data.Entity; 
using System.Linq; 
using System.Web; 
using System.Web.Security; 
using Microsoft.IdentityModel.Clients.ActiveDirectory; 

namespace LEDES.Models 
{ 
    public class ADALTokenCache : TokenCache 
    { 
     private ApplicationDbContext db = new ApplicationDbContext(); 
     private string userId; 
     private UserTokenCache Cache; 

     public ADALTokenCache(string signedInUserId) 
     { 
      // associate the cache to the current user of the web app 
      userId = signedInUserId; 
      this.AfterAccess = AfterAccessNotification; 
      this.BeforeAccess = BeforeAccessNotification; 
      this.BeforeWrite = BeforeWriteNotification; 
      // look up the entry in the database 
      Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId); 
      // place the entry in memory 
      this.Deserialize((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits,"ADALCache")); 
     } 

     // clean up the database 
     public override void Clear() 
     { 
      base.Clear(); 
      var cacheEntry = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId); 
      db.UserTokenCacheList.Remove(cacheEntry); 
      db.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 = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId); 
      } 
      else 
      { 
       // retrieve last write from the DB 
       var status = from e in db.UserTokenCacheList 
          where (e.webUserUniqueId == userId) 
       select new 
       { 
        LastWrite = e.LastWrite 
       }; 

       // if the in-memory copy is older than the persistent copy 
       if (status.First().LastWrite > Cache.LastWrite) 
       { 
        // read from from storage, update in-memory copy 
        Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId); 
       } 
      } 
      this.Deserialize((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits, "ADALCache")); 
     } 

     // Notification raised after ADAL accessed the cache. 
     // If the HasStateChanged flag is set, ADAL changed the content of the cache 
     void AfterAccessNotification(TokenCacheNotificationArgs args) 
     { 
      // if state changed 
      if (this.HasStateChanged) 
      { 
       Cache = new UserTokenCache 
       { 
        webUserUniqueId = userId, 
        cacheBits = MachineKey.Protect(this.Serialize(), "ADALCache"), 
        LastWrite = DateTime.Now 
       }; 
       // update the DB and the lastwrite 
       db.Entry(Cache).State = Cache.UserTokenCacheId == 0 ? EntityState.Added : EntityState.Modified; 
       db.SaveChanges(); 
       this.HasStateChanged = false; 
      } 
     } 

     void BeforeWriteNotification(TokenCacheNotificationArgs args) 
     { 
      // if you want to ensure that no concurrent write take place, use this notification to place a lock on the entry 
     } 

     public override void DeleteItem(TokenCacheItem item) 
     { 
      base.DeleteItem(item); 
     } 
    } 
} 

コールスタックからの情報とCryptographicEsceptionを打つのポイントは、あなたがしませんでした

System.Web.dll!System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.HomogenizeErrors(System.Func<byte[], byte[]> func, byte[] input) Unknown 
    System.Web.dll!System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.Unprotect(byte[] protectedData) Unknown 
    System.Web.dll!System.Web.Security.MachineKey.Unprotect(System.Web.Security.Cryptography.ICryptoServiceProvider cryptoServiceProvider, byte[] protectedData, string[] purposes) Unknown 
    System.Web.dll!System.Web.Security.MachineKey.Unprotect(byte[] protectedData, string[] purposes) Unknown 
> LEDES.dll!LEDES.Models.ADALTokenCache.ADALTokenCache(string signedInUserId) Line 28 C# 
    LEDES.dll!LEDES.Startup.ConfigureAuth.AnonymousMethod__7_0(Microsoft.Owin.Security.Notifications.AuthorizationCodeReceivedNotification context) Line 54 C# 
    Microsoft.Owin.Security.OpenIdConnect.dll!Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationHandler.AuthenticateCoreAsync() Unknown 
    mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.InvokeMoveNext(object stateMachine) Unknown 
    mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown 
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown 
    mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run() Unknown 
    mscorlib.dll!System.Threading.Tasks.AwaitTaskContinuation.InvokeAction(object state) Unknown 
    mscorlib.dll!System.Threading.Tasks.AwaitTaskContinuation.RunCallback(System.Threading.ContextCallback callback, object state, ref System.Threading.Tasks.Task currentTask) Unknown 
    mscorlib.dll!System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.Run(System.Threading.Tasks.Task task, bool canInlineContinuationTask) Unknown 
    mscorlib.dll!System.Threading.Tasks.Task.FinishContinuations() Unknown 
    mscorlib.dll!System.Threading.Tasks.Task.FinishStageThree() Unknown 
    mscorlib.dll!System.Threading.Tasks.Task<System.__Canon>.TrySetResult(System.__Canon result) Unknown 
    mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<Microsoft.Owin.IFormCollection>.SetResult(Microsoft.Owin.IFormCollection result) Unknown 
    Microsoft.Owin.dll!Microsoft.Owin.OwinRequest.ReadFormAsync() Unknown 
    mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.InvokeMoveNext(object stateMachine) Unknown 
    mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown 
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown 
    mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run() Unknown 
    mscorlib.dll!System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation..cctor.AnonymousMethod__8_0(object state) Unknown 
    System.Web.dll!System.Web.AspNetSynchronizationContext.Post.AnonymousMethod__0() Unknown 
    System.Web.dll!System.Web.Util.SynchronizationHelper.SafeWrapCallback(System.Action action) Unknown 
    System.Web.dll!System.Web.Util.SynchronizationHelper.QueueAsynchronous.AnonymousMethod__0(System.Threading.Tasks.Task _) Unknown 
    mscorlib.dll!System.Threading.Tasks.ContinuationTaskFromTask.InnerInvoke() Unknown 
    mscorlib.dll!System.Threading.Tasks.Task.Execute() Unknown 
    mscorlib.dll!System.Threading.Tasks.Task.ExecutionContextCallback(object obj) Unknown 
    mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown 
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown 
    mscorlib.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref System.Threading.Tasks.Task currentTaskSlot) Unknown 
    mscorlib.dll!System.Threading.Tasks.Task.ExecuteEntry(bool bPreventDoubleExecution) Unknown 
    mscorlib.dll!System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() Unknown 
    mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() Unknown 
    mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() Unknown 
    [Native to Managed Transition] 
+0

適切なスタックトレースが問題の理解に役立ちます。 –

+0

スタックトレースを追加 – JQuery

+0

そのスレッドを確認できますか:http://blogs.msdn.com/b/webdev/archive/2012/10/23/cryptographic-improvements-in-asp-net-4-5-pt-2 .aspx .configファイルのmachineKey設定との互換性に関するセクションがあります。 –

答えて

2

これに対する解決策が見つかりました。

エラーが発生したコードのセクションは、AdalToken.Cache.csファイルです。

userId = signedInUserId; 
this.AfterAccess = AfterAccessNotification; 
this.BeforeAccess = BeforeAccessNotification; 
this.BeforeWrite = BeforeWriteNotification; 
// look up the entry in the database 
Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId); 
// place the entry in memory 
this.Deserialize((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits,"ADALCache")); 

特に最後の行です。また

関連があるdb.UserTokenCacheListのコンテキストである:

私はこの新しいプロジェクトを始めたとき、私はAzureの認証を設定するためのウィザードを使用して行ったときにこのすべては、Visual Studioによって生成された
{ 
    public class ApplicationDbContext : DbContext 
    { 
     public ApplicationDbContext() 
      : base("DefaultConnection") 
     { 
     } 

     public DbSet<UserTokenCache> UserTokenCacheList { get; set; } 
    } 

    public class UserTokenCache 
    { 
     [Key] 
     public int UserTokenCacheId { get; set; } 
     public string webUserUniqueId { get; set; } 
     public byte[] cacheBits { get; set; } 
     public DateTime LastWrite { get; set; } 
    } 
} 

ApplicationDbContextのベース( "DefaultConnection")については、

これは私のweb.configにはまだエントリがありませんでしたが、最近までこれは常に有効でした。

ウェブで。config、<内connectionStrings>私のデータベースを指すようにDefaultConnectionの行を追加しましたが、今は少なくとも今のところすべて動作します。

これは、同じエラーが発生した場合に役立ちます。

4

追加スタックトレース

を発生しました。このような無駄な例外メッセージが出る理由を理解することはかなり重要です。 意図的です。 System.Webは、暗号コードが失敗した本当の理由を隠します。あなたは穏やかなエラーメッセージ( "それは動作しませんでした")と失敗した実際のコードのスタックトレースを取得します。

重要ではないので、危険です。攻撃者は意図的に不正なデータであなたのWebアプリケーションを調査し、例外からの知識を得ることができます。

本当の理由を見つけるには、より良いスタックトレースと例外メッセージを取得する必要があります。そのため、例外がスローされたときに停止するようにデバッガに指示する必要があります。本当のもので、穏やかなものではありません。 VS2015では、[デバッグ]> [Windows]> [例外設定]を使用します。 "Common Language Runtime Exceptions"チェックボックスをクリックすると、四角形からチェックマークに変わります。また、[ツール]> [オプション]> [デバッグ]> [一般]> [コードを有効にする]チェックボックスをオフにします。

+0

のおかげで、修理を完了しました。あなたにコメントしたものと同じ、私に別のエラーを与えました。 - http://stackoverflow.com/questions/21985217/mscorlib-pdb-not-上に示したエラーと同じ 'スタックトレース'情報を表示することで終了します。ビットは次に何をするかを失った – JQuery

+0

これはエラーではありません。デバッグ> Windows>コールスタックを使用してスタックトレースを取得します。例外メッセージは出力ウィンドウに表示されます。 –

+0

は、コールスタック – JQuery

15

同じ問題があります。 1時間以上 "ジャッキング"した後、私はメンバーデータベース(Visual Studioで自動作成されることが多い)に入り、UserTokenCachesテーブルからすべての行を削除しました。アプリケーションを実行し、凍結のエラーメッセージを過ぎてしまった。新しいキャッシュトークンレコードが作成され、テーブルに挿入されました。

+0

から情報を追加しました。ありがとう! – marisks

+0

私も同じことをしました...回答を投稿することを考えていましたが、すでにそこにあります。あなたのテーブル "UserTokenCaches"をクリアすると、あなたの問題は解決します –

+0

これは私にとってはうまくいくのですが、私はその理由を知りません。 Azure Websites – jle

関連する問題