【问题标题】:not check Token validation in Asp core 3不在 Asp 核心 3 中检查令牌验证
【发布时间】:2019-12-06 18:21:45
【问题描述】:

我需要用这个检查令牌验证:

 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,但是当我发送请求时它没有检查它。 它没有检查令牌 Validation 。并告诉我UnAuthorize。有什么问题 ?我该如何解决这个问题???

【问题讨论】:

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


    【解决方案1】:

    您的代码中没有任何内容看起来配置错误,但是当我过去尝试解决类似问题时,我会检查一些事项:

    检查 WWW-Authenticate 响应标头

    默认情况下,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;
        },
      };
    

    关闭验证

    对于TokenValidationParameters 的所有验证事件,您都有true。将这些设置为false,然后分别启用每个以查看导致问题的原因。

    【讨论】:

      【解决方案2】:

      您的代码应该可以工作 您的令牌似乎无效。将一些验证参数值更改为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 检查令牌的内容。 此外,如果您使用基于策略的身份验证,则应注册“مدیریت نقشها”策略。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-14
        • 2020-01-31
        • 2020-02-16
        • 1970-01-01
        • 2020-06-22
        • 2017-09-13
        • 1970-01-01
        • 2017-04-29
        相关资源
        最近更新 更多