title: Asp.net Core Web Api returning a 401 when user is logged in
body: <p>I have an Angular front end application connected to an Asp.Net Core Web API backend running on two different ports (front 4200, back 5001) running locally everything runs just fine, but when it is published to the site I am receiving a 401 error when trying to access anything with an Authorize attribute on it. I am seeing the following error on my client side: <code>www-authenticate: Bearer error=&quot;invalid_token&quot;, error_description=&quot;The signature key was not found&quot;</code>
  I am using a JWT to send credentials.</p>
  <p>Here is my startup Configure services code</p>
  <pre><code>services.AddAuthentication(x =&gt;
              {
                  x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
              })
              .AddJwtBearer(options =&gt;
              {
                  options.SaveToken = true;
                  options.TokenValidationParameters = new TokenValidationParameters
                  {
                      ValidateIssuerSigningKey = true,
                      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8 .GetBytes(Configuration.GetSection(&quot;AppSettings:Token&quot;).Value)),
                      ValidateIssuer = false,
                      ValidateAudience = false
                  };
                  
              });
              services.AddCors(options =&gt; {
                  options.AddPolicy(&quot;localhost&quot;, builder =&gt;
                  {
                      builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                  });
              } 
              );
  </code></pre>
  <p>and Configure:</p>
  <pre><code>            app.UseHttpsRedirection();
              app.UseStaticFiles();
              app.UseAuthentication();
              app.UseRouting();
              app.UseCors(options =&gt; options.AllowAnyOrigin());            
              app.UseAuthorization();                             
              app.UseEndpoints(endpoints =&gt;
              {
                  endpoints.MapControllerRoute(
                      name: &quot;default&quot;,
                      pattern: &quot;{controller}/{action=Index}/{id?}&quot;);
              });
  </code></pre>
  <p>appsettings.json:</p>
  <pre><code>&quot;Appsettings&quot;: { &quot;Token&quot;: &quot;Super secret key&quot; }
  </code></pre>
  <p>JWT creation on login:</p>
  <pre><code>        private async Task&lt;string&gt; GenerateJwtToken(User user)
          {
              var claims = new List&lt;Claim&gt;
              {
                  new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                  new Claim(ClaimTypes.Name, user.UserName)
              };
  
              var roles = await _userManager.GetRolesAsync(user);
              foreach (var role in roles)
              {
                  claims.Add(new Claim(ClaimTypes.Role, role));
              }
  
              var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection(&quot;AppSettings:Token&quot;).Value));
  
              var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
  
              var tokenDescriptor = new SecurityTokenDescriptor
              {
                  Subject = new ClaimsIdentity(claims),
                  Expires = DateTime.Now.AddDays(1),
                  SigningCredentials = creds
              };
  
              var tokenHandler = new JwtSecurityTokenHandler();
  
              var token = tokenHandler.CreateToken(tokenDescriptor);
              return tokenHandler.WriteToken(token);
          }
  </code></pre>
  <p>Example of controller method that is throwing 401:</p>
  <pre><code>        [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
          [EnableCors(&quot;localhost&quot;)]
          [HttpGet]
          public IActionResult GetX(int id)
          {
              try
              {
                  return Ok(_repo.GetX(id));
              }
              catch (Exception e)
              {
                  return BadRequest(&quot;Failed to get X: &quot; + id);
              }
          }
  </code></pre>
  <p>I have found other Stack Overflow responses that changed the order of statements in Configure around that I have tried, but every time I have I start get CORS errors. Any help would be greatly appreciated, this has been sending me in circles for days.</p>