title: C# API Gives error 401 in postaman, even when using the generated token
body: <p>I have a api endpoints that allows me to login. Then I have a other api endpoint where I want to get data from.</p>
  <p>Here is a exemple of data that I want to get from my postman As you can see when I use the login endpoint I get a token</p>
  <p><a href="https://i.stack.imgur.com/zXBOL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zXBOL.png" alt="Login" /></a></p>
  <p>Then I want to use the token to get the clients but it does not work I get A 401 here is a image of the problem. As you can see I have used the token but I am still not authorized why is that? Thank you for your help.</p>
  <p><a href="https://i.stack.imgur.com/nyiZb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nyiZb.png" alt="Get Client" /></a></p>
  <p>I have the following Controller to authenticate.</p>
  <pre><code>[Route(&quot;api/auth&quot;)]
  [ApiController]
  public class AuthController : ControllerBase
  {
      private readonly ILogger&lt;AuthController&gt; _logger;
      private readonly IEmployeeService _employeeService;
  
      public AuthController(ILogger&lt;AuthController&gt; logger, IEmployeeService employeeService)
      {
          _logger = logger;
          _employeeService = employeeService;
      }
  
  
      [HttpPost, Route(&quot;login&quot;)]
      public IActionResult Login([FromBody] LoginModel user)
      {
         Employee employeeFromDB = Task.Run(async () =&gt; await _employeeService.GetByUserName(user.UserName)).Result;
  
          if (user == null)
          {
              return BadRequest(&quot;Invalid client request&quot;);
          }
  
          if(employeeFromDB == null) 
          {
              return Unauthorized();
          } 
          else if (user.UserName == employeeFromDB.UserName &amp;&amp; user.Password == &quot;123qwe&quot;)
          {
              var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(&quot;superSecretKey@45&quot;));
              var signingCreditials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
  
              var tokenOptions = new JwtSecurityToken(
                  issuer: &quot;https://localhost:44363/&quot;,
                  audience: &quot;https://localhost:44363/&quot;,
                  claims: new List&lt;Claim&gt;(),
                  expires: DateTime.Now.AddMinutes(5),
                  signingCredentials: signingCreditials
                  );
  
              var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
  
              return Ok(new { Token = tokenString });
          }
  
          return Unauthorized();
      }
  </code></pre>
  <p>I have the following controller that is secured</p>
  <pre><code>    [Route(&quot;api/[controller]&quot;)]
      [ApiController]
      public class ClientsController : ControllerBase
      {
          private readonly ILogger&lt;ClientsController&gt; _logger;
          private readonly IClientService _clientService;
  
          public ClientsController(ILogger&lt;ClientsController&gt; logger, IClientService clientService)
          {
              _logger = logger;
              _clientService = clientService;
          }
  
          // GET api/clients
          [HttpGet]
          [Authorize]
          public IEnumerable&lt;ClientViewModel&gt; Get()
          {
              ClientViewModel clientViewModel;
              List&lt;ClientViewModel&gt; listClientViewModels = new List&lt;ClientViewModel&gt;();
  
              var clients = Task.Run(async () =&gt; await _clientService.GetAllClients()).Result;
  
              foreach (var client in clients) 
              {
                  clientViewModel = new ClientViewModel();
                  clientViewModel.ClientId = client.ClientId;
                  clientViewModel.Active = client.Active;
                  clientViewModel.Address = client.Address;
                  clientViewModel.City = client.City;
                  clientViewModel.ClienteName = client.ClienteName;
                  clientViewModel.ComercialEmployeeId = client.ComercialEmployeeId;
                  clientViewModel.Confirmed = client.Confirmed;
                  clientViewModel.CountryId = client.CountryId;
                  clientViewModel.CreationDate = client.CreationDate;
                  clientViewModel.DANE = client.DANE;
                  clientViewModel.Department = client.Department;
                  clientViewModel.ElectronicBillingEmail = client.ElectronicBillingEmail;
                  clientViewModel.Eliminated = client.Eliminated;
                  clientViewModel.NIT = client.NIT;
                  clientViewModel.PostalCode = client.PostalCode;
                  clientViewModel.Phone = client.Phone;
  
                  listClientViewModels.Add(clientViewModel);
              }
  
              return listClientViewModels;
          }
     }
  }
  </code></pre>
  <p>Here is my startup code</p>
  <pre><code>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(options =&gt;
      {
          options.AddPolicy(&quot;EnableCORS&quot;, builder =&gt; 
          {
              builder.AllowAnyOrigin()
              .AllowAnyHeader()
              .AllowAnyMethod();
          });
      });
  
      services.AddAuthentication(opt =&gt;
      {
          opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
          opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
      }).AddJwtBearer(opttions =&gt;
      {
  
          opttions.TokenValidationParameters = new TokenValidationParameters
          {
              ValidateIssuer = true,
              ValidateAudience = true,
              ValidateLifetime = true,
              ValidateIssuerSigningKey = true,
  
              ValidIssuer = &quot;https://localhost:44363&quot;,
              ValidAudience = &quot;https://localhost:44363&quot;,
              IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(&quot;superSecretKey@45&quot;))
          };
      });
  
      services.AddControllersWithViews();
     
      services.AddSpaStaticFiles(configuration =&gt;
      {
          configuration.RootPath = &quot;ClientApp/dist&quot;;
      });
      
      services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
      services.AddTransient&lt;DatabaseMigrator&gt;();
      services.AddDbContext&lt;erp_colombiaDbContext&gt;(options =&gt; options.UseMySql(
               Configuration.GetConnectionString(&quot;DefaultConnection&quot;),
               optionsBuilder =&gt; optionsBuilder.MigrationsAssembly(typeof(DesignTimeDbContextFactory).Assembly.FullName)));
  
      services.AddDbContext&lt;erp_colombiaDbContext&gt;(options =&gt; options.UseMySql(
              Configuration.GetConnectionString(&quot;DefaultConnection&quot;),
              optionsBuilder =&gt; optionsBuilder.MigrationsAssembly(typeof(DesignTimeDbContextFactory).Assembly.FullName)));
  }
  
  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
      if (env.IsDevelopment())
      {
          app.UseDeveloperExceptionPage();
      }
      else
      {
          app.UseExceptionHandler(&quot;/Error&quot;);
          app.UseHsts();
      }
  
      app.UseHttpsRedirection();
  
      app.UseCors(&quot;EnableCORS&quot;);
  
      app.UseStaticFiles();
      if (!env.IsDevelopment())
      {
          app.UseSpaStaticFiles();
      }
  
      app.UseRouting();
  
      app.UseAuthentication();
      app.UseAuthorization();
  
      app.UseEndpoints(endpoints =&gt;
      {
          endpoints.MapControllerRoute(
              name: &quot;default&quot;,
              pattern: &quot;{controller}/{action=Index}/{id?}&quot;);
      });
  
      app.UseSpa(spa =&gt;
      {
          spa.Options.SourcePath = &quot;ClientApp&quot;;
  
          if (env.IsDevelopment())
          {
              spa.UseAngularCliServer(npmScript: &quot;start&quot;);
          }
      });
  }
  </code></pre>