title: No 'Access-Control-Allow-Origin' header is present on the requested resource error when [Authorize] is placed on any method in a controller
body: <p>I have been following the tutorials <a href="https://damienbod.com/2016/03/02/angular2-openid-connect-implicit-flow-with-identityserver4/" rel="nofollow noreferrer">here</a> to build my application. Everything works well at the authentication side. Now, the problem I am having is when I move to the resource server to retrieve data. If I place the [Authorize] on any method in the resource server I get the error message "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access. The response had HTTP status code 500.". If I remove it everything works fine but I am unable access any claims or roles associated with the user</p>
  
  <p>Excerpts of the startup.cs code of my AuthServer is as follows</p>
  
  <pre><code>public class Startup
  {
      string PublicHostUri { get { return "https://localhost:44354"; } }
      private readonly IHostingEnvironment _environment;
      public Startup(IHostingEnvironment env)
      {
          var builder = new ConfigurationBuilder()
              .SetBasePath(env.ContentRootPath)
              .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
              .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
  
          if (env.IsEnvironment("Development"))
          {
              // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
              builder.AddApplicationInsightsSettings(developerMode: true);
          }
          _environment = env;
          builder.AddEnvironmentVariables();
          Configuration = builder.Build();
      }
  
      public IConfigurationRoot Configuration { get; }
  
  
      public void ConfigureServices(IServiceCollection services)
      {
  
          var connectionString = Configuration["Data:UserAccConnection:ConnectionString"];
          var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
          var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "reportbook.auth.pfx"), "");
  
          var reportbookConnnectionString = Configuration["Data:ReportBookDbConnection:connectionString"];
          services.AddDbContext&lt;ReportBookDbContext&gt;(options =&gt;
              options.UseSqlServer(reportbookConnnectionString));
  
          // Add framework services.
          services.AddApplicationInsightsTelemetry(Configuration);
  
  
          services.AddDbContext&lt;UserDbContext&gt;(options =&gt;
              options.UseSqlServer(connectionString, b =&gt; b.MigrationsAssembly(migrationsAssembly)));
  
          // Register the Identity services.
          services.AddIdentity&lt;ApplicationUser, UserRole&gt;()
              .AddEntityFrameworkStores&lt;UserDbContext, Guid&gt;()
              .AddDefaultTokenProviders();
  
          services.AddCors();
          services.AddMvc();
  
          services.AddIdentityServer()
              .AddDefaultEndpoints()
  
              .AddOperationalStore(builder =&gt;
              builder.UseSqlServer(connectionString,
              options =&gt; options.MigrationsAssembly(migrationsAssembly)))
  
              .AddConfigurationStore(builder =&gt;
              builder.UseSqlServer(connectionString,
              options =&gt; options.MigrationsAssembly(migrationsAssembly)))
  
              .SetSigningCredential(cert)
              .AddAspNetIdentity&lt;ApplicationUser&gt;()
              .AddProfileService&lt;IdentityWithAdditionalClaimsProfileService&gt;();
  
          services.Configure&lt;MvcOptions&gt;(options =&gt;
          {
              options.Filters.Add(new RequireHttpsAttribute());
          });
  
          services.AddTransient&lt;IProfileService, IdentityWithAdditionalClaimsProfileService&gt;();
          services.AddTransient&lt;IUnitOfWorkAsync, UnitOfWork&gt;();
          services.AddScoped&lt;IDataContextAsync, ReportBookDbContext&gt;();
  
  
  
      }
  
      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
      {
          loggerFactory.AddConsole(Configuration.GetSection("Logging"));
          loggerFactory.AddDebug();
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
              app.UseDatabaseErrorPage();
              InitializeDbTestData(app);
          }else
          {
            app.UseExceptionHandler(
            builder =&gt;
            {
                builder.Run(
                  async context =&gt;
                  {
                      context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                      context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
  
                      var error = context.Features.Get&lt;IExceptionHandlerFeature&gt;();
                      if (error != null)
                      {
                          await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
                      }
                  });
            });
          }
  
          app.UseApplicationInsightsRequestTelemetry();
  
          app.UseApplicationInsightsExceptionTelemetry();
  
          app.UseStaticFiles();
          app.UseCors(builder =&gt;
              builder.AllowAnyOrigin()
              .AllowCredentials()
              .AllowAnyHeader()
              .AllowAnyMethod());
  
          app.UseCsp(options =&gt; options.DefaultSources(directive =&gt; directive.Self())
              .ImageSources(directive =&gt; directive.Self()
                 .CustomSources("*"))
              .ScriptSources(directive =&gt; directive.Self()
                  .UnsafeInline())
              .StyleSources(directive =&gt; directive.Self()
                  .UnsafeInline()));
  
          app.UseXContentTypeOptions();
          app.UseXfo(options =&gt; options.Deny());
          app.UseXXssProtection(options =&gt; options.EnabledWithBlockMode());
  
          app.UseIdentity();
          app.UseIdentityServer();
  
          //app.UseMvc(routes =&gt;
          //{
          //    routes.MapRoute(
          //        name: "default",
          //        template: "{controller=Home}/{action=Index}/{id?}");
          //});
  
          app.UseMvcWithDefaultRoute();
          app.UseMvc();
          //databaseInitializer.Seed(app).GetAwaiter().GetResult();
      }
      private static void InitializeDbTestData(IApplicationBuilder app)
      {
          using (var scope = app.ApplicationServices.GetService&lt;IServiceScopeFactory&gt;().CreateScope())
          {
              scope.ServiceProvider.GetRequiredService&lt;PersistedGrantDbContext&gt;().Database.Migrate();
              scope.ServiceProvider.GetRequiredService&lt;ConfigurationDbContext&gt;().Database.Migrate();
              scope.ServiceProvider.GetRequiredService&lt;UserDbContext&gt;().Database.Migrate();
  
              var context = scope.ServiceProvider.GetRequiredService&lt;ConfigurationDbContext&gt;();
  
              if (!context.Clients.Any())
              {
                  foreach (var client in Clients.Get())
                  {
                      context.Clients.Add(client.ToEntity());
                  }
                  context.SaveChanges();
              }
  
  
              if (!context.Scopes.Any())
              {
                  foreach (var clientSope in Scopes.Get())
                  {
                      context.Scopes.Add(clientSope.ToEntity());
                  }
                  context.SaveChanges();
              }
              var userManager = scope.ServiceProvider.GetRequiredService&lt;UserManager&lt;ApplicationUser&gt;&gt;();
              var roleManager = scope.ServiceProvider.GetRequiredService&lt;RoleManager&lt;UserRole&gt;&gt;();
  
              if (!userManager.Users.Any())
              {
                  foreach (var newUser in Users.Get())
                  {
                      ApplicationUser user = new ApplicationUser();
                      user.Id = new Guid();
                      user.EmailConfirmed = true;
                      user.UserName = newUser.Email;
                      user.UserNo = newUser.UserNo;
                      user.FirstName = newUser.FirstName;
                      user.LastName = newUser.LastName;
                      user.Gender = newUser.Gender;
                      user.UserCategory = newUser.UserCategory;
                      user.ZoneInfo = newUser.ZoneInfo;
                      userManager.CreateAsync(user, "Password123!").Wait();
                      userManager.AddClaimAsync(user, new Claim("UserCategory", user.UserCategory)).Wait();
                      foreach (var role in newUser.UserRoles)
                      {
                          if (!roleManager.RoleExistsAsync(role).GetAwaiter().GetResult())
                          {
                              UserRole userRole = new UserRole();
                              userRole.Id = new Guid();
                              userRole.Name = role;
                              roleManager.CreateAsync(userRole).Wait();
                          }
                          userManager.AddToRoleAsync(user, role).Wait();
                          userManager.AddClaimAsync(user, new Claim(JwtClaimTypes.Role, role)).Wait();
                      }
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>Excerpts of  startup.cs file of the resource server is as follows</p>
  
  <pre><code>public class Startup
      {
          private IHostingEnvironment _env { get; set; }
          public Startup(IHostingEnvironment env)
          {
              _env = env;
              var builder = new ConfigurationBuilder()
                  .SetBasePath(env.ContentRootPath)
                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
  
              if (env.IsEnvironment("Development"))
              {
                  // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
                  builder.AddApplicationInsightsSettings(developerMode: true);
              }
  
              builder.AddEnvironmentVariables();
              Configuration = builder.Build();
          }
  
          public IConfigurationRoot Configuration { get; }
          //private static void InitializeDbTestData(IApplicationBuilder app)
          //{
          //    using (var scope = app.ApplicationServices.GetService&lt;IServiceScopeFactory&gt;().CreateScope())
          //    {
          //        scope.ServiceProvider.GetRequiredService&lt;ReportBookDbContext&gt;().Database.Migrate();
          //    }
          //}
  
          // This method gets called by the runtime. Use this method to add services to the container
          public void ConfigureServices(IServiceCollection services)
          {
              var folderForKeyStore = Configuration["Data:keystore:KeyStoreFolderWhichIsBacked"];
              var cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "reportbook.auth.pfx"), "");
  
              services.AddDataProtection()
                  .SetApplicationName("ReportBook")
                  .ProtectKeysWithDpapiNG("CERTIFICATE=Hashid:" + cert.Thumbprint,flags: DpapiNGProtectionDescriptorFlags.None);
  
              services.AddDbContext&lt;ReportBookDbContext&gt;(options =&gt;
                  options.UseSqlServer(Configuration["Data:ReportBookDbConnection:connectionString"],
                  b =&gt; b.MigrationsAssembly("ReportBook.Resource")));         
  
              // Add framework services.
              services.AddCors();
              services.AddApplicationInsightsTelemetry(Configuration);
              services.AddTransient&lt;IEmailSender, AuthMessageSender&gt;();
              services.AddTransient&lt;ISmsSender, AuthMessageSender&gt;();
  
  
  
              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, ILoggerFactory loggerFactory)
          {
              loggerFactory.AddConsole(Configuration.GetSection("Logging"));
              loggerFactory.AddDebug();
  
              app.UseDeveloperExceptionPage();
  
              app.UseStatusCodePagesWithReExecute("/error");
  
              if (env.IsDevelopment())
              {
                  //InitializeDbTestData(app);
              }
  
              JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
  
              IdentityServerAuthenticationOptions identityServerValidationOptions = new IdentityServerAuthenticationOptions
              {
                  Authority = "https://localhost:44354/",
                  ScopeName = "resource_server",
                  ScopeSecret = new IdentityServer4.Models.Secret("scopeSecret".Sha256()).ToString(),
                  AutomaticAuthenticate = true,
                  SupportedTokens = SupportedTokens.Both,
                  AutomaticChallenge = true
              };
              app.UseIdentityServerAuthentication(identityServerValidationOptions);
  
              app.UseApplicationInsightsRequestTelemetry();
  
              app.UseApplicationInsightsExceptionTelemetry();
  
              app.UseExceptionHandler(
                builder =&gt;
                {
                    builder.Run(
                      async context =&gt;
                      {
                          context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                          context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
  
                          var error = context.Features.Get&lt;IExceptionHandlerFeature&gt;();
                          if (error != null)
                          {
                             await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
                          }
                      });
                });
              app.UseCors(builder =&gt;
                  builder.AllowAnyOrigin()
                  .AllowAnyHeader()
                  .AllowAnyMethod()
                  .AllowCredentials());
              app.UseMvc();
          }
      }
  </code></pre>
  
  <p>Below is the an excerpt of the the controller whose method I am trying to reach</p>
  
  <pre><code>[HttpGet("GetInstitutions")]
          //[Authorize]
          public IActionResult GetInstitutions([FromQuery]InstitutionSearchQry model)
          {
              var authorisation = Request.Headers["Authorization"];
              bool auth = User.Identity.IsAuthenticated;
              IEnumerable&lt;Institution&gt; _institutions = null;
              string userCategory = User.Claims.Where(a =&gt; a.Type == "UserCategory").Select(a =&gt; a.Value).FirstOrDefault().ToString();
              string zoneInfo = User.Claims.Where(a =&gt; a.Type == "ZoneInfo").Select(a =&gt; a.Value).FirstOrDefault().ToString();
              string userNo = User.Claims.Where(a =&gt; a.Type == "UserNo").Select(a =&gt; a.Value).FirstOrDefault().ToString();
              bool admin = User.IsInRole("Admin");
  
              List&lt;Student&gt; students = new List&lt;Student&gt;();
  
              //Institution institution = _institutionService.Find(a =&gt; a.InstitutionID == zoneInfo);
              var pagination = Request.Headers["Pagination"];
  
              if (!string.IsNullOrEmpty(pagination))
              {
                  string[] vals = pagination.ToString().Split(',');
                  int.TryParse(vals[0], out page);
                  int.TryParse(vals[1], out pageSize);
              }
  
              switch (userCategory)
              {
                  case "Guardian":
                      {
  
                          students = _guardianService.GetStudents(userNo).ToList();
                          _institutions = _admissionService.GetInstitutions(students.Select(a =&gt; a.StudentID).ToList(),model.StartYear,model.EndYear, s =&gt; s.Term.AcademicYear.Institution.UniversityInstitutes.Select(a =&gt; a.University));
                      }
                      break;
                  case "Student":
                      {
                          _institutions = _admissionService.GetInstitution(userNo,s=&gt;s.Term.AcademicYear.Institution.UniversityInstitutes.Select(a=&gt;a.University));
                      }
                      break;
                  default:
                      {
                          _institutions = _institutionService.GetInstitutions(a =&gt; a.AdministrativeStructure.ZoneInfo == zoneInfo &amp;&amp; a.Level.LevelName==model.Level, page, pageSize, out totalCount, s =&gt; s.AdministrativeStructure, s =&gt; s.Level,s=&gt;s.UniversityInstitutes.Select(a=&gt;a.University));
                      }
                      break;
              }
              if (!String.IsNullOrEmpty(model.Level) &amp;&amp; model.Level != "myschool")
              {
                  _institutions = _institutions.Where(a =&gt; a.Level.LevelName == model.Level);
              }
  
              var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
  
  
              Response.AddPagination(page, pageSize, totalCount,totalPages);
              Response.AddIdentityInfo(userCategory, admin, userNo, zoneInfo);
              IEnumerable&lt;InstitutionDataViewModel&gt; _instDataModel = Mapper.Map&lt;IEnumerable&lt;Institution&gt;, IEnumerable&lt;InstitutionDataViewModel&gt;&gt;(_institutions);
              return new OkObjectResult(_instDataModel);
          }
  </code></pre>
  
  <p>The following is the angular 2 code from where the call is made to the resource server</p>
  
  <pre><code>@Injectable()
  export class InstitutionService {
      private resourceApiUrl: string;
      private headers: Headers;
      private storage: any;
      private actionUrl: string;
      public totalItems: number;
  
  
      constructor(private _http: Http,
          private itemsService: ItemsService,
          private _configuration: Configuration,
          private _router: Router,
          private _authService: AuthService) {
          this.resourceApiUrl = `${_configuration.resourceServer}api/Institution/`;   
      }
      private SetHeaders(page?: number, itemsPerPage?: number) {
          this.headers = new Headers();
          this.headers.append('Content-Type', 'application/json');
          this.headers.append('Accept', 'application/json');
          if (page != null &amp;&amp; itemsPerPage != null) {
              this.headers.append('Pagination', page + ',' + itemsPerPage);
          }
  
          var token = this._authService.GetToken();
          if (token !== "") {
              let tokenValue = 'Bearer ' + token;
              console.log("tokenValue:" + tokenValue);
              this.headers.append('Authorization', tokenValue);
          }
      }
      public GetInstitutions = (InstitutionSearchQry?: any, page?: number, itemsPerPage?: number): Observable&lt;PaginatedResult&lt;IInstitution[]&gt;&gt; =&gt; {
          this.SetHeaders(page, itemsPerPage);
          var paginatedResult: PaginatedResult&lt;IInstitution[]&gt; = new PaginatedResult&lt;IInstitution[]&gt;();
          let options = new RequestOptions({ headers: this.headers, body: '' });
          if (!InstitutionSearchQry.level) {
              this.actionUrl = "GetInstitutions";
          } else {
              this.actionUrl = "GetInstitutions/", InstitutionSearchQry;
  
          }
  
          return this._http.get(this.resourceApiUrl + this.actionUrl, options)
              .map((res: Response) =&gt; {
                  //console.log(res.headers.keys());
                  paginatedResult.result = res.json();
                  if (res.headers.get("Pagination") != null) {
                      //var pagination = JSON.parse(res.headers.get("Pagination"));
                      var paginationHeader: Pagination = this.itemsService.getSerialized&lt;Pagination&gt;(JSON.parse(res.headers.get("Pagination")));
                      paginatedResult.pagination = paginationHeader;
                  }
                  if (res.headers.get("IdentityInfo") != null) {
                      var identityInfo: IdentityInfo = this.itemsService.getSerialized&lt;IdentityInfo&gt;(JSON.parse(res.headers.get("IdentityInfo")));
                      paginatedResult.identityInfo = identityInfo;
                  }
                  this.totalItems = paginatedResult.pagination.TotalItems;
                  return paginatedResult;
              }).catch(this.handleError);
      };
  
  
  }
  </code></pre>
  
  <p>So basically the authorisation information provided at the AuthServer side is not reaching the resource server.
  As one can see I have added the 'CORS' service in both files. </p>