title: Netcore API return 401 even when bearer token is included
body: <p>I want to secure my API endpoint, so that It can only be access over authentication, I end up getting this error. I use the register method to register a user and get a token. I then use that long token in the request header to access a protected area. But I keep getting authorize 401 error. What exactly is happening wrong! </p>
  
  <pre><code>http Get http://localhost:5000/Account/Protected 'authorization:Bearer       eyJhb....fx0IM'
  HTTP/1.1 401 Unauthorized
  Content-Length: 0
  Date: Fri, 27 Jul 2018 12:36:46 GMT
  Server: Kestrel
  WWW-Authenticate: Bearer error="invalid_token", error_description="The token as no expiration"
  </code></pre>
  
  <p>I have this controller configuration for the for the <code>Account Controller</code>. The Register method works well and register the person, now if I want to add a test the api with the Protected Controller. I get the 401 error.</p>
  
  <pre><code>namespace Lemon.Auth.Controllers
  {
  [Route("[controller]/[action]")]
  public class AccountController : ControllerBase
  {
  
      private readonly SignInManager&lt;IdentityUser&gt; _signInManager;
      private readonly UserManager&lt;IdentityUser&gt; _userManager;
      private readonly IConfiguration _configuration;
  
      public AccountController(
          UserManager&lt;IdentityUser&gt; userManager,
          SignInManager&lt;IdentityUser&gt; signInManager,
          IConfiguration configuration
      )
      {
          _userManager = userManager;
          _signInManager = signInManager;
          _configuration = configuration;
      }
  
      [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)
      [HttpGet]
      public async Task&lt;object&gt; Protected()
      {
          return "Protected area";
      }
  
      // Handlers
      [HttpPost]
      public async Task&lt;object&gt; Login([FromBody] LoginDto model)
      {
  
          var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);
  
          if(result.Succeeded)
          {
              var appUser = _userManager.Users.SingleOrDefault(r =&gt; r.Email == model.Email);
              return await GenerateJwtToken(model.Email, appUser);
          }
  
          throw new ApplicationException("Invalid Login Attempt");
      }
  
      // Handler :Register:
      public async Task&lt;object&gt; Register([FromBody] RegisterDto model)
      {
          var user = new IdentityUser
          {
              UserName = model.Email,
              Email = model.Email
          };
  
          // debuggi
          try
          {
              var result = await _userManager.CreateAsync(user, model.Password);
              if (result.Succeeded)
              {
                  await _signInManager.SignInAsync(user, false);
                  return await GenerateJwtToken(model.Email, user);
              }
          }
          catch (System.Exception ex)
          {
              Console.WriteLine(ex.ToString());
          }
  
          throw new ApplicationException("Unknown Error");
      }
  
      private async Task&lt;object&gt; GenerateJwtToken(string email, IdentityUser user)
      {
          var claims = new List&lt;Claim&gt;
          {
              new Claim(JwtRegisteredClaimNames.Sub, email),
              new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
              new Claim(ClaimTypes.NameIdentifier, user.Id)
          };
  
          var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtKey"]));
          var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
          // var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JwtExpiresDays"]));
          Console.WriteLine("hello");
  
          var token = new JwtSecurityToken(
              _configuration["JwtIssuer"],
              _configuration["JwtIssuer"],
              claims,
              signingCredentials: creds
          );
  
          return new JwtSecurityTokenHandler().WriteToken(token);
      }
  }
  }
  </code></pre>
  
  <p>This is my Startup.cs</p>
  
  <pre><code>        public void ConfigureServices(IServiceCollection services)
      {
          // Db and context
          services.AddEntityFrameworkNpgsql().AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
              {
                  options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"));
              }
          );
  
          // add Identity
          services.AddIdentity&lt;IdentityUser, IdentityRole&gt;()
              .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;()
              .AddDefaultTokenProviders();
  
          // add jwt
          JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // clear default behaviour
          services.AddAuthentication(options =&gt; 
          {
              options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
              options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
              options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
          })
          .AddJwtBearer(cfg =&gt; 
          {
              cfg.RequireHttpsMetadata = false;
              cfg.SaveToken = true;
              cfg.TokenValidationParameters = new TokenValidationParameters
                  {
                      ValidIssuer = Configuration["JwtIssuer"],
                      ValidAudience = Configuration["JwtIssuer"],
                      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
                      ClockSkew = TimeSpan.Zero // remove delay of token when expire
  };
              });
  
          // add mvc
          services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
      }
  
      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext dbContext)
      {
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
          }
          else
          {
              app.UseHsts();
          }
  
          // app.UseHttpsRedirection();
          app.UseMvc();
          app.UseAuthentication();
  
          // ensure tables are created
          dbContext.Database.EnsureCreated();
      }
  </code></pre>
  
  <p>All I want to achieve is to protect the API.. I consulted this tutorial <a href="https://medium.com/@ozgurgul/asp-net-core-2-0-webapi-jwt-authentication-with-identity-mysql-3698eeba6ff8" rel="nofollow noreferrer">https://medium.com/@ozgurgul/asp-net-core-2-0-webapi-jwt-authentication-with-identity-mysql-3698eeba6ff8</a></p>