title: JWT token error 401 Unauthorized in .net core 3.1
body: <p>I am learning DDD and JWT so I thought about using both in my application.
  The problem starts like this.
  When I do a resquest with username and password, the api returns the token, but when I put it in the postman's header status 401.</p>
  
  <p>I've tried to put http and https.</p>
  
  <p>LoginController.cs</p>
  
  <pre><code>using System;
  using Microsoft.AspNetCore.Authorization;
  using Microsoft.AspNetCore.Mvc;
  using Grp.Domain.Entities;
  using Grp.Service.Services;
  
  namespace Grp.Api.Controllers
  {
      [Route("api/[controller]")]
      [ApiController]
      public class LoginController : ControllerBase
      {
          private readonly LoginService _loginService;
          private readonly RepresentanteService _representanteService;
          public LoginController(LoginService loginService,
              RepresentanteService representanteService)
          {
              _loginService = loginService;
              _representanteService = representanteService;
          }
  
          // POST: api/Login
          [HttpPost]
          [AllowAnonymous]
          public ActionResult&lt;dynamic&gt; Authenticate([FromBody]Representante representante)
          {
              try
              {
                  representante.Senha = _representanteService.CriptografarSenha(representante.Senha);
                  var usuarioValido = _loginService.UsuarioValido(representante);
  
                  if (!usuarioValido)
                      return BadRequest(new { message = "Usuário ou senha inválidos" });
  
  
                  var token = TokenService.GenerateToken(representante);
                  representante.Senha = "";
  
                  return new
                  {
                      representante,
                      token
                  };
              }
              catch (Exception ex)
              {
                  return BadRequest(ex);
              }
          }
      }
  }
  </code></pre>
  
  <p>ClientesController.cs</p>
  
  <pre><code>using System;
  using Microsoft.AspNetCore.Authorization;
  using Microsoft.AspNetCore.Mvc;
  using Grp.Domain.Entities;
  using Grp.Service.Services;
  using Grp.Service.Validators;
  
  namespace OpersanEM.Api.Controllers
  {
      [Authorize]
      [Route("api/[controller]")]
      [ApiController]
      public class ClientesController : ControllerBase
      {
          private readonly BaseService&lt;Cliente&gt; _service;
          public ClientesController(BaseService&lt;Cliente&gt; service)
          {
              _service = service;
          }
          // GET: api/Clientes
          [HttpGet]
          public IActionResult Get()
          {
              try
              {
                  return new ObjectResult(_service.Get());
              }
              catch (Exception ex)
              {
                  return BadRequest(ex.Message);
              }
          }
  
          // GET: api/Clientes/5
          [HttpGet("{id}")]
          public IActionResult Get(int id)
          {
              try
              {
                  return new ObjectResult(_service.Get(id));
              }
              catch (ArgumentException ex)
              {
                  return NotFound(ex);
              }
              catch (Exception ex)
              {
                  return BadRequest(ex.Message);
              }
          }
  
          // POST: api/Clientes
          [HttpPost]
          public IActionResult Post([FromBody] Cliente item)
          {
              try
              {
                  _service.Post&lt;ClienteValidator&gt;(item);
  
                  return new ObjectResult(item.Id);
              }
              catch (ArgumentNullException ex)
              {
                  return NotFound(ex);
              }
              catch (Exception ex)
              {
                  return BadRequest(ex.Message);
              }
          }
  
          // PUT: api/Clientes/5
          [HttpPut("{id}")]
          public IActionResult Put([FromBody] Cliente item)
          {
              try
              {
                  _service.Put&lt;ClienteValidator&gt;(item);
  
                  return new ObjectResult(item);
              }
              catch (ArgumentNullException ex)
              {
                  return NotFound(ex);
              }
              catch (Exception ex)
              {
                  return BadRequest(ex.Message);
              }
          }
  
          // DELETE: api/ApiWithActions/5
          [HttpDelete("{id}")]
          public IActionResult Delete(int id)
          {
              try
              {
                  _service.Delete(id);
  
                  return new NoContentResult();
              }
              catch (ArgumentException ex)
              {
                  return NotFound(ex);
              }
              catch (Exception ex)
              {
                  return BadRequest(ex.Message);
              }
          }
      }
  }
  </code></pre>
  
  <p>Startup.cs</p>
  
  <pre><code>using Microsoft.AspNetCore.Authentication.JwtBearer;
  using Microsoft.AspNetCore.Builder;
  using Microsoft.AspNetCore.Hosting;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;
  using Microsoft.Extensions.Hosting;
  using Microsoft.IdentityModel.Tokens;
  using Grp.Domain.Entities;
  using Grp.Infra.CrossCutting;
  using Grp.Infra.Data.Context;
  using Grp.Infra.Data.Repository;
  using Grp.Service.Services;
  using System.Text;
  
  namespace Grp.Api
  {
      public class Startup
      {
          public Startup(IConfiguration configuration)
          {
              Configuration = configuration;
          }
  
          public IConfiguration Configuration { get; }
  
          // This method gets called by the runtime. Use this method to add services to the container.
          public void ConfigureServices(IServiceCollection services)
          {
              services.AddCors();
              services.AddControllers();
  
              var key = Encoding.ASCII.GetBytes(Settings.Secret);
              services.AddAuthentication(x =&gt;
              {
                  x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                  x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
              })
              .AddJwtBearer(x =&gt;
              {
                  x.RequireHttpsMetadata = false;
                  x.SaveToken = true;
                  x.TokenValidationParameters = new TokenValidationParameters
                  {
                      ValidateIssuerSigningKey = true,
                      IssuerSigningKey = new SymmetricSecurityKey(key),
                      ValidateIssuer = false,
                      ValidateAudience = false
                  };
              });
  
              services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
              services.AddScoped&lt;SqlContext, SqlContext&gt;();
  
              services.AddScoped&lt;BaseRepository&lt;Cliente&gt;&gt;();
              services.AddScoped&lt;BaseRepository&lt;Representante&gt;&gt;();
  
              services.AddScoped&lt;BaseService&lt;Cliente&gt;&gt;();
              services.AddScoped&lt;BaseService&lt;Representante&gt;&gt;();
              services.AddScoped&lt;RepresentanteService&gt;();
              services.AddScoped&lt;LoginService&gt;();
  
              services.AddScoped&lt;StringCipher&gt;();
  
  
          }
  
          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
          {
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
              }
  
              app.UseStaticFiles();
              app.UseRouting();
  
              app.UseCors(x =&gt; x
              .AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader());
  
              app.UseAuthentication();
              app.UseAuthorization();
  
  
              app.UseEndpoints(endpoints =&gt;
              {
                  endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
              });
          }
      }
  }
  </code></pre>
  
  <p>TokenService.cs</p>
  
  <pre><code>using Microsoft.IdentityModel.Tokens;
  using Grp.Domain.Entities;
  using System;
  using System.IdentityModel.Tokens.Jwt;
  using System.Security.Claims;
  using System.Text;
  
  namespace Grp.Service.Services
  {
      public static class TokenService
      {
          public static string GenerateToken(Representante representante)
          {
              var tokenHandler = new JwtSecurityTokenHandler();
              var key = Encoding.ASCII.GetBytes(Settings.Secret);
              var tokenDescriptor = new SecurityTokenDescriptor
              {
                  Subject = new ClaimsIdentity(new Claim[]
                  {
                      new Claim(ClaimTypes.Name, representante.Nome)
                  }),
                  Expires = DateTime.UtcNow.AddDays(2),
                  SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
              };
              var token = tokenHandler.CreateToken(tokenDescriptor);
              return tokenHandler.WriteToken(token);
          }
      }
  }
  </code></pre>