title: JWT bearer token authorization being applied on exisitng MVC web appication in .NET Core
body: <p>I am trying out Web API's in .net core. I have added an API controller to my existing .net core MVC web application.</p>
  
  <p>I am using JWT Tokens for authorization. I am doing this through the startup class.</p>
  
  <p>The API works just fine.</p>
  
  <p>But as expected the authorization is being applied on the entire MVC application.</p>
  
  <p>Is there a way I can enable authentication through bearer tokens only for the API controllers and not the web application controllers?</p>
  
  <p><strong>Startup.cs:</strong></p>
  
  <pre><code>using System;
  using Microsoft.AspNetCore.Builder;
  using Microsoft.AspNetCore.Identity;
  using Microsoft.AspNetCore.Hosting;
  using Microsoft.AspNetCore.Http;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.EntityFrameworkCore;
  using Project.Data;
  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;
  using Microsoft.AspNetCore.Authentication.JwtBearer;
  using Microsoft.IdentityModel.Tokens;
  using System.Text;
  
  namespace Project
  {
      public class Startup
      {
          public Startup(IConfiguration configuration)
          {
              Configuration = configuration;
          }
  
          public IConfiguration Configuration { get; }
          public bool ValidateAudience { get; private set; }
  
          public void ConfigureServices(IServiceCollection services)
          {
              services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
                  options.UseSqlServer(
                      Configuration.GetConnectionString("DefaultConnection")));
  
              services.AddIdentity&lt;IdentityUser,IdentityRole&gt;()
                  .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;()
                  .AddDefaultTokenProviders();
  
              services.Configure&lt;CookiePolicyOptions&gt;(options =&gt;
              {
                  options.CheckConsentNeeded = context =&gt; true;
                  options.MinimumSameSitePolicy = SameSiteMode.None;
  
              });
  
              services.ConfigureApplicationCookie(options =&gt;
              {
                  options.Cookie.HttpOnly = true;
                  options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
                  options.LoginPath = "/Identity/Account/Login"; 
                  options.LogoutPath = "/Identity/Account/Logout"; 
                  options.AccessDeniedPath = "/Identity/Account/AccessDenied"; 
                  options.SlidingExpiration = true;
              });
  
              services.AddCors();
  
              services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  
              services.AddAuthentication(option =&gt;
              {
                  option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                  option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                  option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
              }).AddJwtBearer(options =&gt;
              {
                  options.SaveToken = true;
                  options.RequireHttpsMetadata = true;
                  options.TokenValidationParameters = new TokenValidationParameters()
                  {
                      ValidateIssuer = true,
                      ValidateAudience = true,
                      ValidAudience = Configuration["Jwt:Site"],
                      ValidIssuer = Configuration["Jwt:Site"],
                      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SigningKey"]))
                  };
              });
  
          }
  
          public void Configure(IApplicationBuilder app, IHostingEnvironment env)
          {
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
                  app.UseDatabaseErrorPage();
              }
              else
              {
                  app.UseExceptionHandler("/Home/Error");
                  app.UseHsts();
              }
  
              app.UseHttpsRedirection();
              app.UseStaticFiles();
              app.UseCookiePolicy();
  
              app.UseAuthentication();
  
              app.UseMvc(routes =&gt;
              {
                  routes.MapRoute(
                      name: "default",
                      template: "{Controller=Startup}/{action=Login}/{id?}");
              });
          }
      }
  }
  </code></pre>
  
  <p><strong>appsettings.json:</strong></p>
  
  <pre><code>{
    "ConnectionStrings": {
      "DefaultConnection": " Data Source=Server; Database = db;Trusted_Connection=True;MultipleActiveResultSets=true"
    },
    "Jwt": {
      "Site": "www.signinkey.com",
      "SigningKey": "ConstantSigningKey",
      "ExpiryInMinutes": "30"
    },
    "Logging": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "AllowedHosts": "*"
  }
  </code></pre>
  
  <p><strong>API controller:</strong></p>
  
  <pre><code>namespace Project.Controllers
  {
      [Route("api/[controller]/[action]")]
      public class AuthController : BaseController
      {
          protected IConfiguration _configuration;
  
          public AuthController(UserManager&lt;IdentityUser&gt; userManager, IConfiguration configuration)
          {
              _userManager = userManager;
              _configuration = configuration;
          }
  
          public string GenerateToken(int size = 32)
          {
              var randomNumber = new byte[size];
              using (var rng = RandomNumberGenerator.Create())
              {
                  rng.GetBytes(randomNumber);
                  return Convert.ToBase64String(randomNumber);
              }
          }
  
          [HttpGet("")]
          [Route("modelList")]
          [Authorize]
          public IEnumerable&lt;ModelList&gt; SupervisorList(string username)
          {
               return db.modelList.Select(x =&gt; x).ToList();
          }
  
          [Route("register")]
          [HttpPost]
          public async Task&lt;ActionResult&gt; Register([FromBody] InputModel reg)
          {
              var user = new IdentityUser { UserName = reg.Email, Email = reg.Email, SecurityStamp = Guid.NewGuid().ToString() };
              var result = await _userManager.CreateAsync(user, reg.Password);
              if (result.Succeeded)
              {
                  await _userManager.AddToRoleAsync(user, "Admin");
              }
              return Ok(new { Username = user.UserName });
  
          }
  
          [Route("login")]
          [HttpPost]
          public async Task&lt;ActionResult&gt; Login([FromBody] InputModel login)
          {
              var user = await _userManager.FindByNameAsync(login.Email);
              if (user != null &amp;&amp; await _userManager.CheckPasswordAsync(user, login.Password))
              {
  
                  var claim = new[]
                  {
                      new Claim(JwtRegisteredClaimNames.Sub, user.UserName)
                  };
                  var signinKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SigningKey"]));
  
                  int expiryInMinutes = Convert.ToInt32(_configuration["Jwt:ExpiryInMinutes"]);
  
                  var token = new JwtSecurityToken(
                      issuer: _configuration["Jwt:Site"],
                      audience: _configuration["Jwt:Site"],
                      expires: DateTime.UtcNow.AddMinutes(expiryInMinutes),
                      signingCredentials: new SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256)
                      );
  
  
                  return Ok(
                      new
                      {
                          token = new JwtSecurityTokenHandler().WriteToken(token),
                          expiration = token.ValidTo
                      });
  
  
              }
              return Unauthorized();
          }
      }
  }
  </code></pre>
  
  <p>As the JWT Token authentication is enabled in the startup class; I am getting an 401 unauthorized code when I try to access the non api controller actions as well.</p>
  
  <p><strong>What I am trying is:</strong></p>
  
  <ol>
  <li>Add an API controller to an existing .net core mvc web application.</li>
  <li><p>Use JWT token authentication only for the API methods and not the web application methods.</p>
  
  <ul>
  <li>Is the above possible? Is it a good practice? How can it be achieved?</li>
  </ul></li>
  </ol>
  
  <p>Need Direction. Thank you:)</p>