title: Prevent redirect to /Account/Login in asp.net core 2.2
body: <p>I am trying to prevent the app to redirect to <code>/Account/Login</code> in asp.net core 2.2 when the user isn't logged in.</p>
  <p>Even though i write <code>LoginPath = new PathString(&quot;/api/contests&quot;);</code> any unauthorized requests are still redirected to <code>/Account/Login</code></p>
  <p>This is my Startup.cs:</p>
  <pre class="lang-cs prettyprint-override"><code>using System;
  using System.Reflection;
  using AutoMapper;
  using Contest.Models;
  using Contest.Tokens;
  using Microsoft.AspNetCore.Authentication.Cookies;
  using Microsoft.AspNetCore.Authorization;
  using Microsoft.AspNetCore.Builder;
  using Microsoft.AspNetCore.Hosting;
  using Microsoft.AspNetCore.Http;
  using Microsoft.AspNetCore.Identity;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.AspNetCore.Mvc.Authorization;
  using Microsoft.EntityFrameworkCore;
  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;
  using Newtonsoft.Json;
  using Swashbuckle.AspNetCore.Swagger;
  
  namespace Contest
  {
      public class Startup
      {
          public IConfiguration Configuration { get; }
  
          public Startup(IConfiguration configuration)
          {
              Configuration = configuration;
          }
  
          // This method gets called by the runtime. Use this method to add services to the container.
          public void ConfigureServices(IServiceCollection services)
          {
  
              services.AddAutoMapper();
  
              // In production, the React files will be served from this directory
              services.AddSpaStaticFiles(configuration =&gt;
              {
                  configuration.RootPath = &quot;clientapp/build&quot;;
              });
  
              // ===== Add our DbContext ========
              string connection = Configuration.GetConnectionString(&quot;DBLocalConnection&quot;);
              string migrationAssemblyName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
              services.AddDbContext&lt;ContestContext&gt;(options =&gt;
                      options.UseSqlServer(connection,
                      sql =&gt; sql.MigrationsAssembly(migrationAssemblyName)));
  
              // ===== Add Identity ========
              services.AddIdentity&lt;User, IdentityRole&gt;(o =&gt;
              {
                  o.User.RequireUniqueEmail = true;
                  o.Tokens.EmailConfirmationTokenProvider = &quot;EMAILCONF&quot;;
                  // I want to be able to resend an `Email` confirmation email
                  // o.SignIn.RequireConfirmedEmail = true; 
              }).AddRoles&lt;IdentityRole&gt;()
                  .AddEntityFrameworkStores&lt;ContestContext&gt;()
                  .AddTokenProvider&lt;EmailConfirmationTokenProvider&lt;User&gt;&gt;(&quot;EMAILCONF&quot;)
                  .AddDefaultTokenProviders();
  
              services.Configure&lt;DataProtectionTokenProviderOptions&gt;(o =&gt;
                  o.TokenLifespan = TimeSpan.FromHours(3)
              );
  
              services.Configure&lt;EmailConfirmationTokenProviderOptions&gt;(o =&gt;
                  o.TokenLifespan = TimeSpan.FromDays(2)
              );
  
              // ===== Add Authentication ========
  
              services.AddAuthentication(o =&gt; o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme)
                  .AddCookie(options =&gt;
                  {
                      options.Cookie.Name = &quot;auth_cookie&quot;;
                      options.Cookie.SameSite = SameSiteMode.None;
                      options.LoginPath = new PathString(&quot;/api/contests&quot;);
                      options.AccessDeniedPath = new PathString(&quot;/api/contests&quot;);
                      options.Events = new CookieAuthenticationEvents
                      {
                          OnRedirectToLogin = context =&gt;
                          {
                              context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                              return Task.CompletedTask;
                          },
                      };
                  });
  
              // ===== Add Authorization ========
  
              services.AddAuthorization(o =&gt;
              {
  
              });
  
              services.AddCors();
  
              // ===== Add MVC ========
              services.AddMvc(config =&gt;
              {
                  var policy = new AuthorizationPolicyBuilder()
                                      .RequireAuthenticatedUser()
                                      .Build();
                  config.Filters.Add(new AuthorizeFilter(policy));
              })
                  .AddJsonOptions(options =&gt; options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore)
                  .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  
              // ===== Add Swagger ========
              services.AddSwaggerGen(c =&gt;
              {
                  c.SwaggerDoc(&quot;v1&quot;, new Info
                  {
                      Title = &quot;Core API&quot;,
                      Description = &quot;Documentation&quot;,
                  });
  
                  var xmlPath = $&quot;{System.AppDomain.CurrentDomain.BaseDirectory}Contest.xml&quot;;
                  c.IncludeXmlComments(xmlPath);
              });
  
          }
  
          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, IHostingEnvironment env)
          {
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
              }
              else
              {
                  app.UseExceptionHandler(&quot;/Error&quot;);
                  app.UseHsts();
              }
  
              app.UseHttpsRedirection();
              app.UseSpaStaticFiles(new StaticFileOptions()
              {
  
              });
  
              app.UseCors(policy =&gt;
              {
                  policy.AllowAnyHeader();
                  policy.AllowAnyMethod();
                  policy.AllowAnyOrigin();
                  policy.AllowCredentials();
              });
  
              app.UseAuthentication();
  
              app.UseMvc();
  
              if (env.IsDevelopment())
              {
                  app.UseSwagger();
                  app.UseSwaggerUI(c =&gt;
                  {
                      c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;Core API&quot;);
                  });
              }
  
              app.UseSpa(spa =&gt;
              {
                  spa.Options.SourcePath = &quot;clientapp&quot;;
  
                  if (env.IsDevelopment())
                  {
                      // spa.UseReactDevelopmentServer(npmScript: &quot;start&quot;);
                      spa.UseProxyToSpaDevelopmentServer(&quot;http://localhost:3000&quot;);
                  }
              });
  
          }
  
      }
  }
  </code></pre>
  <p>I managed to bypass this by creating a controller to handle this route:</p>
  <pre class="lang-cs prettyprint-override"><code>[Route(&quot;/&quot;)]
  [ApiController]
  public class UnauthorizedController : ControllerBase
  {
      public UnauthorizedController()
      {
  
      }
  
      [HttpGet(&quot;/Account/Login&quot;)]
      [AllowAnonymous]
      public IActionResult Login()
      {
          HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
          return new ObjectResult(new
          {
              StatusCode = StatusCodes.Status401Unauthorized,
              Message = &quot;Unauthorized&quot;,
          });
      }
  
  }
  </code></pre>
  <p>What is wrong with my setup?
  Thanks</p>