简体   繁体   中英

ASP.NET Core 3.1 CORS configuration gone wrong

The application is configured to use HTTPS. We want to be able to make calls from the client to a printer on their local network that exposes a simple api that uses HTTP. So from our javascript code we do a POST with a "text/plain" payload to send commands to the printer. When we send this request we get the following error.

jquery-3.3.1.min.js:2 Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://.../pstprnt'. This request has been blocked; the content must be served over HTTPS.

Is there a way to configure CORS in such a way that only this traffic from and to a printer can be done using HTTP while the rest of the application uses HTTPS, without specifying the target IN startup.cs ? ( this is because the printers should be able to be expanded at runtime, so basically just 'allow all orgins', so that its not restricted to the ones specified in Startup.cs)

I have tried multiple guides online, but I'm guessing there is something wrong with our Startup.cs file structure.

The request to the printer looks like this:

$.ajax({
    type: "POST",
    url: "http://<printer-ip>/pstprnt",
    data: 'some ZPL',
    contentType: 'text/plain'
}).done((res) => {
    console.log("second success");
}).fail((e) => {
    alert(e);
})

Here is a snippet our Startup file.

CONFIGURE SERVICES

        public void ConfigureServices(IServiceCollection services)
        {
            // Add Cors
            services.AddCors();

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            /* (Verification/password reset) email sender */
            //services.AddTransient<IEmailSender, EmailSender>();
            //services.Configure<AuthMessageSenderOptions>(Configuration);

            Task.Run(() => {
                var options = new DbContextOptionsBuilder<ApplicationDbContext>().UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).Options;
                using (var dbContext = new ApplicationDbContext(options)) {
                    var model = dbContext.AankoopProduct;
                  
                }
            });



            services.AddLocalization();
            /*
               I commented this out because I am using UseEndpoints, Am I doing this correctly?

            services.AddMvc()
                .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                .AddDataAnnotationsLocalization().AddNewtonsoftJson(options =>
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
            */
          
            services.AddIdentity<Gebruiker, IdentityRole>(options =>
            {
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
                options.SignIn.RequireConfirmedEmail = true;
            }).AddEntityFrameworkStores<ApplicationDbContext>()
              .AddDefaultTokenProviders();

            services.Configure<IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit = true;
                options.Password.RequireLowercase = true;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = true;
                options.Password.RequiredLength = 6;
                options.Password.RequiredUniqueChars = 1;
            });

            services.AddControllersWithViews().AddNewtonsoftJson(options =>
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            // .cshtml views & .razor components 
            services.AddRazorPages();

            //SignalR for Websockets
            services.AddSignalR();

            // reload views after changing JS 
#if DEBUG
            var mvcBuilder = services.AddControllersWithViews();
            mvcBuilder.AddRazorRuntimeCompilation();
            #endif


            services.ConfigureApplicationCookie(opts => opts.LoginPath = "/Account/Login");

            /* Breadcrumbs */
            services.AddBreadcrumbs(GetType().Assembly, options =>
            {
                options.TagName = "nav";
                options.TagClasses = "";
                options.OlClasses = "breadcrumb breadcrumb--transparent m-0";
                options.LiClasses = "breadcrumb-item";
                options.ActiveLiClasses = "breadcrumb-item active";
                //options.SeparatorElement = "<li class=\"separator\">/</li>";
            });
            /* Repositories */
            services.RegisterRepositories();

            services.AddSession();
        }


CONFIGURE

   public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IVerkoopProductXMLRepository rep)
        {
            //app.ApplicationServices.GetService<IInkomendeBestellingTrackerSingleton>();


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            #region Auth
            var supportedCultures = new[]
            {
                new CultureInfo("nl-BE")
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("nl-BE"),
                // Formatting numbers, dates, etc.
                SupportedCultures = supportedCultures,
                // UI strings that we have localized.
                SupportedUICultures = supportedCultures
            });

            var cultureInfo = new CultureInfo("nl-BE");
            cultureInfo.NumberFormat.CurrencySymbol = "€";
            cultureInfo.NumberFormat.NumberDecimalSeparator = ".";

            CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
            CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("nl-BE");
            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("nl-BE");


            // To configure external authentication, 
            // see: http://go.microsoft.com/fwlink/?LinkID=532715

            #endregion

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseStatusCodePages();
            app.UseRouting();
            app.UseSession();

            // Enable Cors
            app.UseCors();
            /*
              I commented this out because I am using UseEndpoints() , Am I doing this correctly?
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=UserSelection}/{id?}");
            });
            */
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Account}/{action=Login}/{id?}");
            });

 }


This doesn't relate to your ASP.NET CORS configuration, because you're making a request directly from the client (the browser) to the printer; CORS would come into play if you were making cross-domain requests to the ASP.NET API.

What you could do is make the request to the printer from the server, instead, assuming your network topology permits it. Make an AJAX request from your JS to a new endpoint on the server, which then makes a plain HTTP request to the printer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM