-1

I know this is asked multiple times but none of the answers I have found have seemed to help me.

I have a .NET Core 3.1 Web API running using Windows Authentication and HTTP. The service is functioning (i.e I can browse to http://localhost:3545/users and it returns exactly what I expect).

To enable CORS I have followed several tutorials/demos and none seem to work. This is what I have added:

In Startup.cs:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder.WithOrigins("http://localhost:4200")
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

I then have an Angular Web App that attempts to call this API. The Angular Web App is running on http://localhost:4200 and calls this:

this.http.get<User>('http://localhost:3545/users')

The error returned in the console is: Access to XMLHttpRequest at 'http://localhost:3545/users' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am struggling where to go from here, so any help would be greatly appreciated.

UPDATE It appears to work if I enable "anonymousAuthentication" in the launchSettings.json file. I don't want to do this though as the API then doesn't appear to user Windows Authentication and I can no longer access the user of the request using: HttpContext.User.Identity.Name

Thanks David

dkearsley
  • 13
  • 1
  • 5

1 Answers1

-1

I've been able to fix the issue.

In the http GET request I needed to add "{ withCredentials: true }"

i.e: this.http.get('https://localhost:44315/users', { withCredentials: true });

Wasn't clear to me in any of the documentation but at least I have it working now and hopefully this will help someone else out in the future.

dkearsley
  • 13
  • 1
  • 5