简体   繁体   English

如何调试JWT承载错误“ invalid_token”

[英]How to debug JWT Bearer Error “invalid_token”

I'm trying to secure an existing AspNet Core 2.0 / angular 4 app using jwt. 我正在尝试使用jwt保护现有的AspNet Core 2.0 / angular 4应用程序。 I'm using angular2-jwt for the client part and it works just fine. 我在客户端部分使用angular2-jwt,它工作得很好。 However when it comes to my WebApi, my token is always rejected(using AuthHttp from angular2-jwt to launch my requests or even with postman). 但是,当涉及到我的WebApi时,我的令牌始终被拒绝(使用angular2-jwt中的AuthHttp发起我的请求,甚至使用邮递员)。 The only response I get is 401 Bearer error="invalid_token". 我得到的唯一响应是401 Bearer error =“ invalid_token”。 I've checked it with the jwt.io chrome extension and it seems just fine(signature, audience, issuer). 我已经用jwt.io chrome扩展名检查了它,看起来还不错(签名,受众,发行者)。 I can't find anything in the IIS logs either as to why it is deemed invalid. 我为什么在IIS日志中找不到任何有关为什么认为无效的内容。 So my question is how can I get more information on what is wrong with the token ? 所以我的问题是,我如何才能获得有关令牌故障的更多信息? Any help will be much appreciated. 任何帮助都感激不尽。

For reference here's my startup.cs 供参考,这是我的startup.cs

public class Startup
  {

public static void Main(string[] args)
{
  var host = new WebHostBuilder()
      .UseKestrel()
      .UseContentRoot(Directory.GetCurrentDirectory())
      .UseIISIntegration()
      .UseStartup<Startup>()
      .Build();

  host.Run();
}
public Startup(IHostingEnvironment env)
{
  var builder = new ConfigurationBuilder()
      .SetBasePath(env.ContentRootPath)
      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
      .AddEnvironmentVariables();
  Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{

  IConfigurationSection jwtConf = this.Configuration.GetSection("jwt");

  services.Configure<Controls.JWTConf>(Configuration.GetSection("jwt"));


  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
     .AddJwtBearer(options =>
     {
       options.TokenValidationParameters =
                       new TokenValidationParameters
                       {
                         ValidateIssuer = true,
                         ValidateAudience = true,
                         ValidateLifetime = true,
                         ValidateIssuerSigningKey = true,
                         ValidIssuer = jwtConf.GetValue<string>("issuer"),
                         ValidAudience = jwtConf.GetValue<string>("audience"),
                         IssuerSigningKey = Security.JwtSecurityKey.Create(jwtConf.GetValue<string>("keyBase"))
                       };
     });



  services.AddMvc(
          config =>
          {
            var policy = new AuthorizationPolicyBuilder()
                             .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                             .RequireClaim(ClaimTypes.Name)
                             .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
          }
    ).AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

  services.AddNodeServices();

  string conn = this.Configuration.GetConnectionString("optimumDB");

  services.AddDbContext<TracDbContext>(options =>
      options.UseSqlServer(conn));

  // Register the Swagger generator, defining one or more Swagger documents
  services.AddSwaggerGen(c =>
  {
    c.SwaggerDoc("v1", new Info { Title = "Angular 4.0 Universal & ASP.NET Core advanced starter-kit web API", Version = "v1" });
  });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, TracDbContext context)
{
  loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  loggerFactory.AddDebug();

  app.UseStaticFiles();


  app.UseAuthentication();

  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
    app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
    {
      HotModuleReplacement = true,
      HotModuleReplacementEndpoint = "/dist/__webpack_hmr"
    });
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
      c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.


    app.MapWhen(x => !x.Request.Path.Value.StartsWith("/swagger", StringComparison.OrdinalIgnoreCase), builder =>
    {
      builder.UseMvc(routes =>
      {
        routes.MapSpaFallbackRoute(
            name: "spa-fallback",
            defaults: new { controller = "Home", action = "Index" });
      });
    });
  }
  else
  {
    app.UseMvc(routes =>
    {
      routes.MapRoute(
       name: "default",
       template: "{controller=Home}/{action=Index}/{id?}");

      routes.MapRoute(
       "Sitemap",
       "sitemap.xml",
       new { controller = "Home", action = "SitemapXml" });

      routes.MapSpaFallbackRoute(
        name: "spa-fallback",
        defaults: new { controller = "Home", action = "Index" });

    });
    app.UseExceptionHandler("/Home/Error");

  }
}

  }

My token generating controller 我的代币生成控制器

  [Route("api/token")]
  [AllowAnonymous]
  public class TokenController : Controller
  {

private IOptions<JWTConf> jwt;

public TokenController(IOptions<JWTConf> jwtConf)
{
  this.jwt = jwtConf;
}

[HttpPost]
public IActionResult Create([FromBody]string userCode)
{
  Model.Entities.Utilisateur user = new Model.Entities.Utilisateur { ID_UTILISATEUR = 6 };

  JwtToken token = new JwtTokenBuilder()
                      .AddSecurityKey(JwtSecurityKey.Create(this.jwt.Value.keyBase))
                      .AddSubject("User")
                      .AddIssuer(this.jwt.Value.issuer)
                      .AddAudience(this.jwt.Value.audience)
                      .AddClaim(ClaimTypes.Name,user.ID_UTILISATEUR.ToString())
                      .AddExpiry(1440)
                      .Build();

  var tok = new { token = token.Value };

  //return Ok(token);
  return Ok(JsonConvert.SerializeObject(tok));
}
  }

And finally the controller that rejects the token : 最后是拒绝令牌的控制器:

  [Produces("application/json")]
  public class JobsController : BaseController
  {
public JobsController(IConfiguration config, TracDbContext db) : base(config, db)
{

}

// GET: api/Jobs
[HttpGet]
[Route("api/Jobs")]
public IEnumerable<Departement> Get()
{
  return new GroupedJobs(Db.GetJobs().ToList());
}

[HttpGet]
[Route("api/Jobs/{id}")]
public JOB_CLIENT Get(int id)
{
  return Db.GetDetailsJob(id);
}

 }

Found the problem ... turns out I was storing my token with quotes around it. 发现了问题。。。原来我正在用令牌将引号括起来。 So The authorization header that was being sent looked like this 因此,正在发送的授权标头如下所示

Bearer "TOKEN" 承载“令牌”

instead of 代替

Bearer TOKEN 不记名代币

Being new to the whole thing I tought the quotes were being added by the AuthHtpp and were part of the protocol. 作为新手,我坚信引号由AuthHtpp添加,并且是协议的一部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JWT Bearer 不断返回 401 状态 - Bearer error="invalid_token", error_description="签名无效" - JWT Bearer Keeps returning 401 Status - Bearer error="invalid_token", error_description="The signature is invalid" ASP.NET Core WebAPI: Bearer error=&quot;invalid_token&quot;, error_description=&quot;未找到签名密钥&quot; - ASP.NET Core WebAPI: Bearer error="invalid_token", error_description="The signature key was not found" Azure B2C Bearer error=“invalid_token”,error_description=“未找到签名密钥” - Azure B2C Bearer error=“invalid_token”, error_description=“The signature key was not found” 为什么我在 asp.net webapi 中收到“Bearer error="invalid_token""? - Why i'm getting "Bearer error="invalid_token"" in asp.net webapi? 如何使无记名令牌无效 - How to make Bearer token invalid 如何从Safari作为客户端从WebAPI获取JWT承载令牌? - How to get JWT bearer token from WebAPI with Safari as the client? 如何在Asp.net Web API中撤销JWT承载令牌 - How to revoke JWT Bearer Token in Asp.net Web API 如何从 JWT 令牌中获取不记名令牌(system.identitymodel.token.jwt.jwtsecuritytoken) - how to get bearer token out of JWT token (system.identitymodel.token.jwt.jwtsecuritytoken) 在每个API请求上重新生成JWT承载令牌 - Regenerate JWT bearer token on each API request 从 swagger UI 传递 header 中的 Jwt 令牌作为不记名令牌不起作用 - Passing Jwt token in header from swagger UI as bearer token not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM