title: Why is Azure Active Directory Authentication causing an character encoding error in my ASP.NET Core Application?
body: <p>I have an ASP.NET Core 2.2 application that I'm making which uses KendoUI as part of its framework.  I recently set up the bones of my application and then, using the built-in wizard of Visual Studio 2019, I added Azure Active Directory Authentication.  This created an app registration for me in Azure that would authenticate users against my company's active directory.</p>
  
  <p>The problem is, when I now run my application, I get the following error and no page loads: </p>
  
  <blockquote>
    <p>The character encoding of the plain text document was not declared.
    The document will render with garbled text in some browser
    configurations if the document contains characters from outside the
    US-ASCII range. The character encoding of the file needs to be
    declared in the transfer protocol or file needs to use a byte order
    mark as an encoding signature.</p>
  </blockquote>
  
  <p>Further investigation into this message shows more details that are:</p>
  
  <blockquote>
    <p>Error loading this URI: Protocol error (unknownError): Could not load
    the source for <a href="https://localhost:44379/" rel="nofollow noreferrer">https://localhost:44379/</a>. [Exception... "Component
    returned failure code: 0x80470002 (NS_BASE_STREAM_CLOSED)
    [nsIInputStream.available]"  nsresult: "0x80470002
    (NS_BASE_STREAM_CLOSED)"  location: "JS frame ::
    resource://devtools/shared/DevToolsUtils.js :: onResponse :: line 555"
    data: no] Stack:
    onResponse@resource://devtools/shared/DevToolsUtils.js:555:34
    onStopRequest@resource://gre/modules/NetUtil.jsm:123:17 Line: 555,
    column: 0</p>
  </blockquote>
  
  <p>I looked at everything that was affected during the addition of AAD and the following files within my project were changed.</p>
  
  <ul>
  <li>appSettings.json</li>
  <li>Startup.cs</li>
  <li>Extensions (folder)</li>
  <li><code>[Authorise]</code> placed in <code>HomeController.cs</code></li>
  <li>AzureAD (folder)</li>
  </ul>
  
  <p>Having used AAD before in my applications, I expect to see these files changed but I've never had problems with the application running afterward.  I started to investigate what possible change could be causing the problem.  After some work, I realize that, if I remove <code>[Authorize]</code> from my controller, everything loads OK.</p>
  
  <p>I'm guessing this is a potential routing issue to my app registration perhaps?  I'm not sure, I need some help as the message is a bit of a red herring as it suggests that there is an HTML formatting issue.  I need some guidance as to what's going wrong.</p>
  
  <p>Here is my code and project structure.</p>
  
  <p><strong>Structure</strong></p>
  
  <p>I always separate my UI from my class libraries, since AAD doesn't change files in the Data, Repo or Services libraries I won't include them in this question for brevity.</p>
  
  <ul>
  <li>MyCompany.Data</li>
  <li>MyCompany.Repo</li>
  <li>MyCompany.Services</li>
  <li>MyCompany.UI</li>
  </ul>
  
  <p><strong>MyCompany.UI/Controllers/HomeController.cs</strong></p>
  
  <pre><code>using MyCompany.Data;
  using Kendo.Mvc.UI;
  using Microsoft.AspNetCore.Mvc;
  using System.Diagnostics;
  using MyCompany.Services;
  using Kendo.Mvc.Extensions;
  using Microsoft.AspNetCore.Authorization;
  
  namespace MyCompany.Controllers
  {
      [Authorize]
      public class HomeController : Controller
      {
          private readonly IVesselService _service;
  
          public HomeController(IVesselService vesselService)
          {
              _service = vesselService;
          }
          public IActionResult Index()
          {
              return View();
          }
          public IActionResult Privacy()
          {
              return View();
          }
          public ActionResult ReadVessels([DataSourceRequest]DataSourceRequest request)
          {
              var vessel = _service.GetVessels();
              return Json(vessel.ToDataSourceResult(request));
          }
          [AcceptVerbs("Post")]
          public ActionResult CreateVessel([DataSourceRequest] DataSourceRequest request, Vessel vessel)
          {
              if (vessel != null &amp;&amp; ModelState.IsValid)
              {
                  _service.InsertVessel(vessel);
              }
  
              return Json(new[] { vessel }.ToDataSourceResult(request, ModelState));
          }
          [AcceptVerbs("Post")]
          public ActionResult UpdateVessel([DataSourceRequest] DataSourceRequest request, Vessel vessel)
          {
              if (vessel != null &amp;&amp; ModelState.IsValid)
              {
                  _service.UpdateVessel(vessel);
              }
  
              return Json(new[] { vessel }.ToDataSourceResult(request, ModelState));
          }
          [AcceptVerbs("Post")]
          public ActionResult DestroyVessel([DataSourceRequest] DataSourceRequest request, Vessel vessel)
          {
              if (vessel != null)
              {
                  _service.DeleteVessel(vessel.Id);
              }
  
              return Json(new[] { vessel }.ToDataSourceResult(request, ModelState));
          }
  
          [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
          public IActionResult Error()
          {
              return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
          }
      }
  }
  </code></pre>
  
  <p><strong>MyCompany.UI/Startup.cs</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;
  using Microsoft.AspNetCore.Builder;
  using Microsoft.AspNetCore.Hosting;
  using Microsoft.AspNetCore.Authentication;
  using Microsoft.AspNetCore.Authentication.JwtBearer;
  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;
  using Microsoft.Extensions.Logging;
  using Microsoft.Extensions.Options;
  using Microsoft.AspNetCore.Mvc;
  using Newtonsoft.Json.Serialization;
  using MyCompany.Repo;
  using Microsoft.EntityFrameworkCore;
  using MyCompany.Services;
  
  namespace MyCompany
  {
      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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                 // Maintain property names during serialization. See:
                 // https://github.com/aspnet/Announcements/issues/194
                 .AddJsonOptions(options =&gt; options.SerializerSettings.ContractResolver = new DefaultContractResolver());
  
              // Database Context
              services.AddDbContext&lt;MyCompanyContext&gt;(options =&gt;
                  options.UseSqlServer(Configuration.GetConnectionString("MyCompanyConnection"), b =&gt; b.MigrationsAssembly("MyCompany.Repo")));
  
              //Repository Scope
              services.AddScoped(typeof(IRepository&lt;&gt;), typeof(Repository&lt;&gt;));
              services.AddTransient&lt;IVesselService, VesselService&gt;();
  
              //Azure AD Authentication
              services.AddAuthentication(sharedOptions =&gt;
              {
                  sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
              }).AddAzureAdBearer(options =&gt; Configuration.Bind("AzureAd", options));
  
              //Add KendoUI Services to services container
              services.AddKendo();
  
              services.AddMvc();
          }
  
          // 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("/Home/Error");
                  // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                  app.UseHsts();
              }
              app.UseHttpsRedirection();
              app.UseCookiePolicy();
              app.UseStaticFiles();
              app.UseAuthentication();
              app.UseMvc(routes =&gt;
              {
                  routes.MapRoute(
                      name: "default",
                      template: "{controller=Home}/{action=Index}/{id?}");
              });
          }
      }
  }
  </code></pre>
  
  <p><strong>MyCompany/appsettings.json</strong></p>
  
  <pre><code>{
    "Logging": {
      "LogLevel": {
        "Default": "Warning",
        "System": "Information",
        "Microsoft": "Information"
      }
    },
    "ConnectionStrings": {
      "MyCompanyConnection": "Server=tcp:mydatabase.database.windows.net,0000;Initial Catalog=MyDatabase;Persist Security Info=False;User ID=Cloud;Password=Midgar1997!;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
    },
    "AllowedHosts": "*",
    "AzureAd": {
      "ClientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
      "Domain": "mycompany.onmicrosoft.com",
      "Instance": "https://login.microsoftonline.com/",
      "TenantId": "xxxxxxxx",
      "CallbackPath": "/signin-oidc",
      "ClientSecret": "xxxxxx",
      "AppIDURL": "https://mycompany.onmicrosoft.com/MyCompany.UI",
      "ConfigView": "MVC"
    }
  }
  </code></pre>
  
  <p>So, that's the code that is directly tied to AAD, I'm not sure if it's a routing issue or maybe, incorrect config of app registration.  I need some help please.</p>