title: Why don't my unauthorized controllers return 401 ASP.Net Core?
body: <p>I'm using Visual studio code and I'm using dot net core framework for a RestAPI. When I access do a controller with "Authorize" attribute, it should return a 401 request but it doesn't return anything in postman. Just a blank.</p>
  
  <p>I think it should comes from my startup code.</p>
  
  <p>I'll share you my configure method in startup file.</p>
  
  <p>Best thanks for your help. If you can find a solution on internet, just share it (I already look for but... Maybe I didn't type the right keyword.)</p>
  
  <p>public class Startup
      {
          public Startup(IConfiguration configuration)
          {
              Configuration = configuration;
          }</p>
  
  <pre><code>    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)
      {
          ConfigureContext(services);
  
          services.AddCors();
          services.AddAutoMapper(typeof(Startup));
  
          // configure strongly typed settings objects
          var appSettingsSection = Configuration.GetSection("AppSettings");
          services.Configure&lt;AppSettings&gt;(appSettingsSection);
  
          // configure jwt authentication
          var appSettings = appSettingsSection.Get&lt;AppSettings&gt;();
          var key = Encoding.ASCII.GetBytes(appSettings.Secret);
          services.AddAuthentication(x =&gt;
          {
              x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
              x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
          })
          .AddJwtBearer(x =&gt;
          {
              x.Events = new JwtBearerEvents
              {
                  OnTokenValidated = context =&gt;
                  {
                      var userService = context.HttpContext.RequestServices.GetRequiredService&lt;IUserService&gt;();
                      var userId = int.Parse(context.Principal.Identity.Name);
                      var user = userService.GetById(userId);
                      if (user == null)
                      {
                          // return unauthorized if user no longer exists
                          context.Fail("Unauthorized");
                      }
                      return Task.CompletedTask;
                  }
              };
              x.RequireHttpsMetadata = false;
              x.SaveToken = true;
              x.TokenValidationParameters = new TokenValidationParameters
              {
                  ValidateIssuerSigningKey = true,
                  IssuerSigningKey = new SymmetricSecurityKey(key),
                  ValidateIssuer = false,
                  ValidateAudience = false
              };
          });
  
          // Register the Swagger generator, defining 1 or more Swagger documents
          services.AddSwaggerGen(c =&gt;
          {
              c.SwaggerDoc("v1", new OpenApiInfo
              {
                  Title = "dotnetcore-api-core",
                  Version = "v1"
              });
          });
          services.AddScoped&lt;IUserService, UserService&gt;();
          services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
      }
  
      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
          app.UseAuthentication();
          app.UseMvc();
          app.UseStaticFiles();
          app.UseHttpsRedirection();
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
          }
          else
          {
              // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
              app.UseHsts();
          }
  
          // Enable middleware to serve generated Swagger as a JSON endpoint.
          app.UseSwagger();
          // Security JWT
          app.UseCors(x =&gt; x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
  
          // 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", "dotnetcore-api-core V1");
          });
      }
  
      public void ConfigureContext(IServiceCollection services)
      {
          // Database injection
          services.AddDbContext&lt;UserContext&gt;(options =&gt;
              options.UseMySql(Configuration.GetConnectionString("AppDatabase")));
      }
  }
  </code></pre>
  
  <p>My controller that doesn't return 401 unauthorized:</p>
  
  <pre><code>    [Authorize]
      [Route("api/users")]
      [ApiController]
      public class UserController : ControllerBase
      {
          private readonly IUserService _userService;
          private IMapper _mapper;
  
          public UserController(
              IUserService userService,
              IMapper mapper)
          {
              _userService = userService;   
              _mapper = mapper;
          }
  
          [HttpGet]
          public async Task&lt;ActionResult&lt;IEnumerable&lt;User&gt;&gt;&gt; GetUsers()
          {
              IEnumerable&lt;User&gt; users = await _userService.GetAll();
  
              if(users == null)
              {
                  return NotFound();
              }
  
              return Ok(users);
          }
  </code></pre>
  
  <p>I followed this tutorial -> <a href="https://jasonwatmore.com/post/2018/08/14/aspnet-core-21-jwt-authentication-tutorial-with-example-api" rel="noreferrer">https://jasonwatmore.com/post/2018/08/14/aspnet-core-21-jwt-authentication-tutorial-with-example-api</a></p>
  
  <p>An example image in postman : <a href="https://i.stack.imgur.com/SfKzp.png" rel="noreferrer">Image example of empty body postman</a></p>