2016-09-08 117 views
0

使用JwtBearerAuthentication中間件時,調用JwtSecurityTokenHandler.WriteToken()後,RSACryptoServiceProvider和其他對象將置於SigningCredentials中。我的問題與此問題非常相似:https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/477JwtBearerAuthentication安全句柄異常

第一個請求有效,但後續任何請求均失敗。此功能在RC2偉大的工作......但現在,我們已經升級到1.0,WriteToken導致:

System.ObjectDisposedException was unhandled by user code HResult=-2146232798 Message=Safe handle has been closed ObjectName="" Source=mscorlib StackTrace: at System.Security.Cryptography.Utils._GetKeyParameter(SafeKeyHandle hKey, UInt32 paramID) at System.Security.Cryptography.RSACryptoServiceProvider.get_KeySize() at Microsoft.IdentityModel.Tokens.RsaSecurityKey.get_KeySize() at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.ValidateAsymmetricSecurityKeySize(SecurityKey key, String algorithm, Boolean willCreateSignatures) at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, String algorithm, Boolean willCreateSignatures) at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures) at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, String algorithm) at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.CreateEncodedSignature(String input, SigningCredentials signingCredentials) at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token) at Api.Controllers.TokenController.CreateToken(EmployeeSecurityRecord record, DateTime expires) in C:\SOURCE\Api\Procede.Excede.Api.Core\src\Api\Controllers\TokenController.cs:line 115 at Api.Controllers.TokenController.Post(ResourceTokenRequest request) in C:\SOURCE\Api\Procede.Excede.Api.Core\src\Api\Controllers\TokenController.cs:line 35 at lambda_method(Closure , Object , Object[]) at Microsoft.AspNetCore.Mvc.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionFilterAsync>d__28.MoveNext() InnerException: 

我找不到在JwtBearerAuthentication的正確使用任何偉大的文檔無論是。有什麼想法嗎?下面是我的實現......

在Startup.cs:

ConfigureServices:

 var keyFile = Configuration["AppSettings:Secret"]; 
     var keyParams = RSAKeyUtils.GetKeyParameters(Path.Combine(Environment.ContentRootPath, keyFile)); 

     var provider = new RSACryptoServiceProvider(); 
     provider.ImportParameters(keyParams); 
     var key = new RsaSecurityKey(provider); 

     _tokenOptions = new TokenAuthOptions 
     { 
      Audience = Configuration["AppSettings:Audience"], 
      Issuer = Configuration["AppSettings:Issuer"], 
      TokenLife = Convert.ToInt32(Configuration["AppSettings:TokenLife"]), 
      Key = key, 
      SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature) 
     }; 

配置:

 app.UseJwtBearerAuthentication(new JwtBearerOptions 
     { 
      TokenValidationParameters = new TokenValidationParameters 
      { 
       IssuerSigningKey = _tokenOptions.Key, 
       ValidAudience = _tokenOptions.Audience, 
       ValidIssuer = _tokenOptions.Issuer, 
       ValidateLifetime = true, 
       ClockSkew = TimeSpan.FromMinutes(1) 
      } 
     }); 

創建通過控制器方法的標記:

private string CreateToken(EmployeeSecurityRecord record, DateTime expires) 
    { 
     var identity = new ClaimsIdentity(
      new GenericIdentity(record.EmpId, "TokenAuth"), 
      new[] 
      { 
       new Claim("tid", "TBD", ClaimValueTypes.String), 
       new Claim("branch_id", record.BrnId, ClaimValueTypes.String), 
       new Claim("wid", record.WspId.ToString(), ClaimValueTypes.Integer), 
       new Claim("roles", "TBD", ClaimValueTypes.String), 
       new Claim("alt_sub", record.AltEmpId ?? "", ClaimValueTypes.String), 
       new Claim("alt_wid", record.AltWspId == null ? "" : record.AltWspId.ToString(), 
        ClaimValueTypes.Integer), 
       new Claim("alt_roles", "TBD", ClaimValueTypes.String) 
      }); 

     var handler = new JwtSecurityTokenHandler(); 

     var descriptor = new SecurityTokenDescriptor 
     { 
      Issuer = _tokenOptions.Issuer, 
      Audience = _tokenOptions.Audience, 
      SigningCredentials = _tokenOptions.SigningCredentials, 
      Subject = identity, 
      Expires = expires 
     }; 

     var token = handler.CreateToken(descriptor); 

     return handler.WriteToken(token); 

回答

0

來自Github上的Microsoft團隊:

庫正在處置它未創建的rsa對象。我們解決這個問題的一個可能的解決方法是在創建簽名後基於JwtSecurityTokenHandler調用CryptoProviderFactory.ReleaseSignatureProvider。您可以設置您自己的CPF並覆蓋ReleaseSignatureProvider。 RSP位於調用圖中,將處理rsa。 SigningCredentials。 CryptoProviderFactory是設置您的CustomProviderFactory的便利場所。

我可以嘗試覆蓋解決方案,如果我有時間...否則,我會等待5.0.1版本發佈。

GitHub Link