使用 System.IdentityModel.Tokens.Jwt - 5.1.4 更新从 1.1 迁移到 2.0 后,JWTAuthentication 在 asp.net core 2.0 中不起作用

San*_*isy 5 c# asp.net asp.net-mvc jwt asp.net-core

错误

错误 CS0619 'JwtBearerAppBuilderExtensions.UseJwtBearerAuthentication(IApplicationBuilder, JwtBearerOptions)' 已过时:'请参阅https://go.microsoft.com/fwlink/?linkid=845470 '

这是 JWT 身份验证的代码

app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = key,
                    ValidAudience = tokenOptions.Audience,
                    ValidIssuer = tokenOptions.Issuer,

                    // When receiving a token, check that it is still valid.
                    ValidateLifetime = true,

                    // This defines the maximum allowable clock skew - i.e. provides a tolerance on the token expiry time 
                    // when validating the lifetime. As we're creating the tokens locally and validating them on the same 
                    // machines which should have synchronised time, this can be set to zero. Where external tokens are
                    // used, some leeway here could be useful.
                    ClockSkew = TimeSpan.FromMinutes(0)
                }
            });
Run Code Online (Sandbox Code Playgroud)

相同的代码在 asp.net core 1.1 I 中运行良好,刚刚从 core 1.1 迁移到 core 2.0 并将 System.IdentityModel.Tokens.Jwt(5.1.1) 更新到 (5.1.4)

配置服务

RSAParameters keyParams = RsaKeyUtils.GetRandomKey();
            key = new RsaSecurityKey(keyParams);
            tokenOptions = new TokenAuthOptions()
            {
                Audience = TokenAudience,
                Issuer = TokenIssuer,
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)
            };
            services.AddSingleton<TokenAuthOptions>(tokenOptions);
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme??)
                    .RequireAuthenticatedUser().Build());
            });
Run Code Online (Sandbox Code Playgroud)

我尝试了这个问题Authentication in dot net core preview-2.0 中发布的解决方案。但该解决方案不起作用,因为 IServiceCollection 不包含 AddJwtBearerAuthentication 的定义,因此出现错误

试图执行https://github.com/aspnet/Security/blob/c5b566ed4abffac4cd7011e0465e012cf503c871/samples/JwtBearerSample/Startup.cs#L47-L53 https://github.com/IdentityServer/IdentityServer4/issues/1055 https://开头的博客.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/

500内部服务器错误。

相同的代码在 asp.net core 1.1 上运行良好。升级到 2.0 时出现问题。

请任何人让我知道我该如何解决这个问题。

Kir*_*kin 3

ASP.NET Core 2.0 中添加 Jwt 承载身份验证的方法已更改。查看您链接的示例的最新版本。

您需要将 Jwt 承载身份验证流程注册为服务,而不是中间件组件。相关代码见ConfigureServices

services.AddAuthentication(...)
    .AddJwtBearer(...);
Run Code Online (Sandbox Code Playgroud)

试试这个ConfigureServices

services.AddAuthentication()
    .AddJwtBearer(jwt =>
    {
        jwt.TokenValidationParameters = new TokenValidationParameters
        {
            IssuerSigningKey = key,
            ValidAudience = tokenOptions.Audience,
            ValidIssuer = tokenOptions.Issuer,

            // When receiving a token, check that it is still valid.
            ValidateLifetime = true,

            // This defines the maximum allowable clock skew - i.e. provides a tolerance on the token expiry time
            // when validating the lifetime. As we're creating the tokens locally and validating them on the same
            // machines which should have synchronised time, this can be set to zero. Where external tokens are
            // used, some leeway here could be useful.
            ClockSkew = TimeSpan.FromMinutes(0)
        };
     });

services.AddAuthorization(auth =>
{
     auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
             .RequireAuthenticatedUser()
             .Build());
});
Run Code Online (Sandbox Code Playgroud)

并确保你有这个Configure

app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)

由于我无法针对您的场景进行测试,因此它很可能第一次无法工作。当您包含由此产生的任何进一步信息时,请务必具体说明。