2

Everyone!

I am struggling to configure CORS in Asp.Core project.

This is my Startup.cs file:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Mvc.Cors.Internal;

namespace Api
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
                .AddJsonFormatters()
                .AddAuthorization();
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder => builder.WithOrigins("http://localhost:54540").AllowAnyHeader().AllowAnyMethod().AllowCredentials());
            }
            );

            services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
            });
        }

        public void Configure(IApplicationBuilder app)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
            {
                Authority = "http://localhost:54540",
                RequireHttpsMetadata = false,

                ScopeName = "api1",
                AutomaticAuthenticate = true
            });

            app.UseMvc();

            app.UseCors("AllowSpecificOrigin");
        }
    }
}

Here is my request:

$.ajax({
                type: "GET",
                url: "http://localhost:1773/Claims/",
                headers: {
                    Authorization: "Bearer " + getUrlParameter("access_token"),
                },
                xhrFields: {
                    withCredentials: true
                }
            }).done(function (data) {
                alert(data);
            });

I am getting this response:

XMLHttpRequest cannot load http://localhost:1773/Claims/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:54540' is therefore not allowed access. The response had HTTP status code 500.

I have added [EnableCors("AllowSpecificOrigin")] in my controller.

I will be very thankful if someone can help me with this.

svick
  • 236,525
  • 50
  • 385
  • 514
Dani
  • 444
  • 1
  • 3
  • 10

1 Answers1

1

If you add the MVC/IdentityServer middleware before the CORS middleware it will not work since the IdentityServer middleware (assuming /Claims is handled by it) will handle the request and does not invoke the later MVC and CORS middleware.

Thomas
  • 5,080
  • 27
  • 42