【问题标题】:JwtBearerAuthentication Safe Handle ExceptionJwtBearerAuthentication 安全处理异常
【发布时间】:2017-01-16 23:55:21
【问题描述】:

在使用 JwtBearerAuthentication 中间件时,调用 JwtSecurityTokenHandler.WriteToken() 后,RSACryptoServiceProvider 和其他对象被放置在 SigningCredentials 中。我的问题和这个问题很相似:https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/477.

第一个请求有效,但任何后续请求都失败。此功能在 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 中:

配置服务:

        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);

【问题讨论】:

    标签: c# asp.net-core-mvc jwt .net-core bearer-token


    【解决方案1】:

    来自 Github 上的 Microsoft 团队:

    库正在处理一个不是它创建的 rsa 对象。我们得到此修复的一种可能的解决方法是基于创建签名后调用 CryptoProviderFactory.ReleaseSignatureProvider 的 JwtSecurityTokenHandler。您可以设置自己的 CPF 并覆盖 ReleaseSignatureProvider。 RSP 在将处理 rsa 的调用图中。签名证书。 CryptoProviderFactory 是设置您的 CustomProviderFactory 的方便场所。

    如果有时间,我可能会尝试覆盖解决方案...否则,我将等待 5.0.1 版本发布。

    GitHub Link

    【讨论】:

      猜你喜欢
      • 2018-03-06
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 2015-01-29
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      相关资源
      最近更新 更多