不检查Asp core 3中的令牌验证

时间:2019-12-06 09:41:00

标签: c# asp.net asp.net-core asp.net-core-3.0

我需要检查令牌验证:

 public static void AddJWTAuthnticationInjection(this IServiceCollection services,SiteSetting siteSetting)
        {
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            var securityKey = Encoding.UTF8.GetBytes(siteSetting.JwtSetting.SecretKey);
            var ValidatePrameters = new TokenValidationParameters
            {
                //Tlorance for Expire Time and Befor Time of Token .
                ClockSkew = TimeSpan.Zero,
                RequireSignedTokens = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(securityKey),
                // I Need Check Expire Token or Not
                RequireExpirationTime = true,
                ValidateLifetime = true,
                ValidateAudience = true,
                ValidAudience = siteSetting.JwtSetting.Audience,
                ValidateIssuer = true,
                ValidIssuer = siteSetting.JwtSetting.Issuer

            };
            options.SaveToken = true;
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters = ValidatePrameters;
        });
    }

我在项目中使用了这种中间件:

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors(builder => builder
                     .AllowAnyHeader()
                     .AllowAnyMethod()
                     .SetIsOriginAllowed((host) => true)
                     .AllowCredentials()
                    );
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

这是我的服务:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining<CreateRoleValidator>());
        services.Configure<SiteSetting>(Configuration.GetSection(nameof(SiteSetting)));
        services.AddControllers().AddControllersAsServices();
        services.AddContext(Configuration);
        services.AddLoginngBehavior();
        services.RegisterRedis(Configuration);
        services.AddMediatR();
        services.AddCors();
        services.Injection();
        **services.AddJWTAuthnticationInjection(_siteSetting);**
    }

但是当我在此控制器中发送带有令牌的请求时:

    [Authorize]
[Pemission("مدیریت نقش ها")]
public class RoleController : BaseController
{
    [HttpGet]
    [Authorize]
    [Pemission("لیست نقش ها")]
    public async Task<ReturnResult<IList<Role>>> GetRoles()
    {
        var result = await mediator.Send(new GetAllRoleQuery());
        if (result.Success)
        {
            return Ok(result.Result);
        }
        return BadRequest(result.ErrorMessage);
    }


}

当我启动项目时,它获得了这项服务AddJWTAuthnticationInjection,但是当我发送请求时,它没有进行检查。 它没有检查令牌验证。并给我看UnAuthorize。有什么问题 ?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

您的代码中没有任何内容看起来会因配置错误而跳出来,但是,当我过去尝试解决类似问题时,有几件事需要检查:

检查WWW身份验证响应标头

默认情况下,asp.net将添加一个WWW-Authenticate标头,该标头可以揭示失败的原因。它可以帮助您找出问题所在(例如,密钥无效吗?还是听众?)。标头值将类似于Bearer error="invalid_token", error_description="The token is expired"

令牌有效吗?

将令牌复制并粘贴到jwt.io中。到期是您所期望的吗?检查发行人/受众等。

检查身份验证事件

JwtBearerOptions有一个Events property,可用于挂接到不同的事件并有助于跟踪问题。下面是将它们连接起来,在每个事件中添加断点或记录日志的一个示例,非常方便。

.AddJwtBearer(options =>
{
  options.Events = new JwtBearerEvents {
    OnChallenge = context => {
      Console.WriteLine("OnChallenge:");
      return Task.CompletedTask;
    },
    OnAuthenticationFailed = context => {
      Console.WriteLine("OnAuthenticationFailed:");
      return Task.CompletedTask;
    },
    OnMessageReceived = context => {
      Console.WriteLine("OnMessageReceived:");
      return Task.CompletedTask;
    },
    OnTokenValidated = context => {
      Console.WriteLine("OnTokenValidated:");
      return Task.CompletedTask;
    },
  };

关闭验证

对于true的所有验证事件,您都有TokenValidationParameters。将它们设置为false,然后分别启用每个按钮,以查看是哪个引起了该问题。

答案 1 :(得分:1)

您的代码应该可以正常工作看来您的令牌无效。将一些验证参数值更改为false,例如以下代码:

var ValidatePrameters = new TokenValidationParameters
        {
            //Tlorance for Expire Time and Befor Time of Token .
            ClockSkew = TimeSpan.Zero,
            RequireSignedTokens = true,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(securityKey),
            // I Need Check Expire Token or Not
            RequireExpirationTime = true,
            ValidateLifetime = false,
            ValidateAudience = false,
            ValidAudience = siteSetting.JwtSetting.Audience,
            ValidateIssuer = false,
            ValidIssuer = siteSetting.JwtSetting.Issuer

        };

然后使用“ jwt.io”上的SecurityKey检查令牌的内容。 此外,如果您使用的是基于策略的身份验证,则应注册“مدیریتنقشها”策略。