使用System.IdentityModel.Tokens.Jwt从5.1迁移到2.0后,JWTAuthentication无法在asp.net core 2.0中运行 - 5.1.4更新

时间:2017-09-09 09:29:20

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

错误

错误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)
                }
            });

相同的代码在asp.net核心1.1中运行良好,我只是从核心1.1迁移到核心2.0并将System.IdentityModel.Tokens.Jwt(5.1.1)更新为(5.1.4)

ConfigureServices

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

我尝试了此问题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://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/

500内部服务器错误。

相同的代码在asp.net核心1.1上完美运行。升级到2.0时会出现问题。

请有人告诉我如何解决此问题。

1 个答案:

答案 0 :(得分:3)

在ASP.NET Core 2.0中添加Jwt Bearer身份验证的方法已更改。请参阅您链接的示例的latest version

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

services.AddAuthentication(...)
    .AddJwtBearer(...);

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

并确保在Configure

中有此功能
app.UseAuthentication();

由于我无法针对您的情况对此进行测试,因此它有机会第一次获胜。当您包含来自此的任何进一步信息时,请务必具体。