title: JWT bearer token Authorization not working asp net core web api
body: <p>I created a web api that uses JWT tokens for authorization with a role based policy (based on 
   <a href="https://jasonwatmore.com/post/2019/10/16/aspnet-core-3-role-based-authorization-tutorial-with-example-api" rel="noreferrer">this</a> article).
  The user logs in generates a token that is used for authorization. I successfully generate the token but when I start to use it to access restricted API actions with it it doesn't work and keeps giving me the 401 HTTP error (I cant even debug considering the action call doesn't trigger). What am I doing wrong?.</p>
  
  <p>Classes:</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.AddControllers();
          services.AddScoped&lt;ICountriesService, CountriesService&gt;();
          services.AddScoped&lt;ICompanyService, CompanyService&gt;();
          services.AddScoped&lt;IPlaneServices, PlaneService&gt;();
          services.AddScoped&lt;IPlaneTypeService, PlaneTypeService&gt;();
          services.AddScoped&lt;ICitiesService, CitiesService&gt;();
          services.AddScoped&lt;IAirfieldService, AirfieldService&gt;();
          services.AddScoped&lt;ITicketTypeService, TicketTypeService&gt;();
          services.AddScoped&lt;IFlightService, FlightService&gt;();
          services.AddScoped&lt;ILuxuryService, LuxuryService&gt;();
          services.AddScoped&lt;IUserService, UserService&gt;();
  
          // Register the Swagger generator, defining 1 or more Swagger documents
          services.AddSwaggerGen(c =&gt;
          {
              c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My API", Version = "v1" });
  
  
              c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
              {
                  Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n 
                    Enter 'Bearer' [space] and then your token in the text input below.
                    \r\n\r\nExample: 'Bearer 12345abcdef'",
                  Name = "Authorization",
                  In = ParameterLocation.Header,
                  Type = SecuritySchemeType.ApiKey,
                  Scheme = "Bearer"
              });
  
              c.AddSecurityRequirement(new OpenApiSecurityRequirement()
            {
              {
                new OpenApiSecurityScheme
                {
                      Reference = new OpenApiReference
                        {
                          Type = ReferenceType.SecurityScheme,
                          Id = "Bearer"
                        },
                        Scheme = "oauth2",
                        Name = "Bearer",
                        In = ParameterLocation.Header,
  
                      },
                      new List&lt;string&gt;()
                    }
              });
              //        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
              //var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
              //c.IncludeXmlComments(xmlPath);
          });
  
          services.AddAutoMapper(cfg =&gt; cfg.AddProfile&lt;Mapper.Mapper&gt;(),
                            AppDomain.CurrentDomain.GetAssemblies());
  
          services.AddDbContext&lt;FlightMasterContext&gt;();
  
  
          services.AddCors();
  
          var secret = Configuration.GetValue&lt;string&gt;(
              "AppSettings:Secret");
  
          var key = Encoding.ASCII.GetBytes(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
              };
          });
  
  
  
      }
  
      // 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();
          }
  
          // Enable middleware to serve generated Swagger as a JSON endpoint.
          app.UseSwagger();
  
          // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
          // specifying the Swagger JSON endpoint.
          app.UseSwaggerUI(c =&gt;
          {
              c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
              c.RoutePrefix = string.Empty;
          });
  
  
  
          app.UseHttpsRedirection();
  
          app.UseRouting();
  
          app.UseAuthorization();
          app.UseAuthentication();
  
          // global cors policy
          app.UseCors(x =&gt; x
              .AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader());
  
          app.UseEndpoints(endpoints =&gt;
          {
              endpoints.MapControllers();
  
          });
      }
  }
  </code></pre>
  
  <p>The controller:</p>
  
  <pre><code>[Route("api/[controller]")]
  [ApiController]
  [Authorize]
  public class AaTestController : ControllerBase
  {
  
      private FlightMasterContext db { get; set; }
  
      private IUserService _userService;
  
      public AaTestController(FlightMasterContext db, IUserService userService)
      {
          this.db = db;
          _userService = userService;
      }
  
      [AllowAnonymous]
      [HttpPost("authenticate")]
      public IActionResult Authenticate([FromBody]AuthenticateModel model)
      {
          var user = _userService.Authenticate(model.Username, model.Password);
  
          if (user == null)
              return BadRequest(new { message = "Username or password is incorrect" });
  
          return Ok(user);
      }
      //DOESNT TRIGGER
      [Authorize(Roles = Role.Admin)]
      [HttpGet]
      public IActionResult GetAll()
      {
          var users = _userService.GetAll();
          return Ok(users);
      }
  
      [HttpGet("{id}")]
      public IActionResult GetById(int id)
      {
          // only allow admins to access other user records
          var currentUserId = int.Parse(User.Identity.Name);
          if (id != currentUserId &amp;&amp; !User.IsInRole(Role.Admin))
              return Forbid();
  
          var user = _userService.GetById(id);
  
          if (user == null)
              return NotFound();
  
          return Ok(user);
      }
  }
  </code></pre>
  
  <p>Service used for authentication and authorization:</p>
  
  <pre><code>public interface IUserService
  {
      User Authenticate(string username, string password);
      IEnumerable&lt;User&gt; GetAll();
      User GetById(int id);
  }
  
  public class UserService : IUserService
  {
      // users hardcoded for simplicity, store in a db with hashed passwords in production applications
      private List&lt;User&gt; _users = new List&lt;User&gt;
      {
          new User { Id = 1, FirstName = "Admin", LastName = "User", Username = "admin", Password = "admin", Role = Role.Admin },
          new User { Id = 2, FirstName = "Normal", LastName = "User", Username = "user", Password = "user", Role = Role.User }
      };
  
  
  
  
  
  
      public User Authenticate(string username, string password)
      {
          var user = _users.SingleOrDefault(x =&gt; x.Username == username &amp;&amp; x.Password == password);
  
  
  
          var secret = "THIS IS Ughjgjhgjhghgighiizgzigiz";
  
  
  
          // return null if user not found
          if (user == null)
              return null;
  
          // authentication successful so generate jwt token
          var tokenHandler = new JwtSecurityTokenHandler();
          var key = Encoding.ASCII.GetBytes(secret);
          var tokenDescriptor = new SecurityTokenDescriptor
          {
              Subject = new ClaimsIdentity(new Claim[]
              {
                  new Claim(ClaimTypes.Name, user.Id.ToString()),
                  new Claim(ClaimTypes.Role, user.Role)
              }),
              Expires = DateTime.UtcNow.AddDays(7),
              SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
          };
          var token = tokenHandler.CreateToken(tokenDescriptor);
          user.Token = tokenHandler.WriteToken(token);
  
          return user.WithoutPassword();
      }
  
      public IEnumerable&lt;User&gt; GetAll()
      {
          return _users.WithoutPasswords();
      }
  
      public User GetById(int id)
      {
          var user = _users.FirstOrDefault(x =&gt; x.Id == id);
          return user.WithoutPassword();
      }
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/curHR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/curHR.png" alt="enter image description here"></a></p>