为什么Authorize属性不会导致HTTP 401用于JWT的未授权请求

时间:2018-03-11 14:21:45

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

我有一个Web API应用程序,我希望用JWT保护,如下Startup

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["Jwt:Issuer"],
                ValidAudience = Configuration["Jwt:Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
            };
        });
    services.AddMvc();
}

我在app.UseAuthentication();方法中也有Startup.Configure。当我使用Postman发出未经授权的请求时,我没有得到任何回复,只是一个空白的身体,当我允许匿名对同一个动作时,我得到了预期的结果。如果我提出授权请求,我也会得到预期的结果。当我发出未经授权的请求时,我会期待HTTP 401,而不仅仅是没有发生任何事情。

我哪里错了?

1 个答案:

答案 0 :(得分:0)

不确定。也许您需要配置挑战方案。下面适用于我(.NET Core 2.x)。

public static IServiceCollection AddJwtValidation(this IServiceCollection services)
        {
            IServiceProvider sp = services.BuildServiceProvider();
            ConfigRoot = sp.GetRequiredService<IConfigurationRoot>();

            tokenAudience = ConfigRoot["JwtToken:Audience"];
            tokenIssuer = ConfigRoot["JwtToken:Issuer"];

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Audience = tokenAudience;
                options.ClaimsIssuer = tokenIssuer;

                options.TokenValidationParameters = new TokenValidationParameters
                {                    
                    // The signing key must match!
                    ValidateIssuerSigningKey = true,
                    RequireSignedTokens = true,
                    IssuerSigningKeyResolver = MyIssuerSigningKeyResolver,

                    // Validate the JWT lifetime.  Note that if 'exp' is present, then it is validated.  If it 
                    // is missing, then the lifetime validation is not done.
                    ValidateLifetime = true,
                    RequireExpirationTime = false,
                    LifetimeValidator = null, //MyLifetimeValidator,

                    // Validate the JWT Issuer (iss) claim
                    ValidateIssuer = true,
                    ValidIssuer = tokenIssuer,

                    // Validate the JWT Audience (aud) claim
                    ValidateAudience = true,
                    ValidAudience = tokenAudience,
                };

                // Override the default ValidateToken method with a custom method.
                options.SecurityTokenValidators.Clear();
                options.SecurityTokenValidators.Add(new MyJwtSecurityTokenHandler());
            });

        return services;
    }