Openiddict-core: Cross-Origin Request Blocked

Created on 8 Jul 2018  ·  2Comments  ·  Source: openiddict/openiddict-core

Hi there...

I am using openiddict with password flow.
I recently updated my app to RC3, and have been trying anything, but nothing succeeds.
I using a different port for backend (1111) and frontend (2222), both running local and work well when using RC2 version.

and this is my error.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:7788//connect/token. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Here is my startup.cs code:
`// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();

        services.AddDbContext<ApplicationDbContext>(options =>
        {
            // Configure the context to Db as mentioned in appsettings.json
                options.UseNpgsql(Configuration["ConnectionStrings:DefaultConnection"], b => b.MigrationsAssembly("WebAPI"));
            }

            options.UseOpenIddict<int>();
        });

        // Register the Identity services.
        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // Configure Identity options and password complexity here
        services.Configure<IdentityOptions>(options =>
        {               
            options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
            options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
            options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
        });

        // Register the OpenIddict services.
        services.AddOpenIddict()
            .AddCore(options =>
            {
                options
                    .UseEntityFrameworkCore()
                    .UseDbContext<ApplicationDbContext>()
                    .ReplaceDefaultEntities<int>();
            })

            .AddServer(options =>
            {
                // Register the ASP.NET Core MVC binder used by OpenIddict.
                // Note: if you don't call this method, you won't be able to
                // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
                options.UseMvc();

                // Enable the token endpoint (required to use the password flow).
                options.EnableTokenEndpoint("/connect/token");

                // Allow client applications to use the grant_type=password flow.
                // Note: the Mvc.Client sample only uses the code flow and the password flow, but you
                // can enable the other flows if you need to support implicit or client credentials.
                //options.AllowAuthorizationCodeFlow()
                options.AllowPasswordFlow()
                       .AllowRefreshTokenFlow();

                // Allow client not provided any client_id
                options.AcceptAnonymousClients();

                // Disable scope validation/checking.
                options.DisableScopeValidation();

                // During development, you can disable the HTTPS requirement.
                options.DisableHttpsRequirement();
            });
            //// Register the OpenIddict validation handler.
            //// Note: the OpenIddict validation handler is only compatible with the
            //// default token format or with reference tokens and cannot be used with
            //// JWT tokens. For JWT tokens, use the Microsoft JWT bearer handler.
            //.AddValidation();

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = OAuthValidationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OAuthValidationDefaults.AuthenticationScheme;
        }).AddOAuthValidation();

        // Repositories
        services.AddScoped<IUnitOfWork, HttpUnitOfWork>();
        services.AddScoped<IAccountManager, AccountManager>();

        services.AddTransient<IApplicationDbInitializer, ApplicationDbInitializer>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });

        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug(LogLevel.Warning);
        loggerFactory.AddFile(Configuration.GetSection("Logging"));

        Util.ConfigureLogger(loggerFactory);

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // Enforce https during production
            //var rewriteOptions = new RewriteOptions()
            //    .AddRedirectToHttps();
            //app.UseRewriter(rewriteOptions);

            app.UseExceptionHandler("/Home/Error");
        }

        app.UseCors(builder => builder
            .AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod());

        app.UseStaticFiles();
    }`

Any helps would be greatly appreciated.
Ronald

question

Most helpful comment

Hi,

The error clearly indicates it's a CORS issue. Try to move app.UseCors() before app.UseAuthentication().

All 2 comments

Hi,

The error clearly indicates it's a CORS issue. Try to move app.UseCors() before app.UseAuthentication().

OMG... Thank you so much @PinpointTownes , you saved my day 👍
and thank you for super fast response.

Was this page helpful?
0 / 5 - 0 ratings