Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Linx 98 posts 258 karma points
    Jul 20, 2023 @ 13:18
    Linx
    0

    Local CORS error. Help to eradicate errors

    Hi

    im running a Umbraco 9 site locally and in the browser console window i see this error

    Access to XMLHttpRequest at 'http://localhost:57127/0ca30041d0ac496399e12c35e1d24301/browserLinkSignalR/negotiate?requestUrl=https%3A%2F%2Flocalhost%3A44378%2F&browserName=&userAgent=Mozilla%2F5.0+(Windows+NT+10.0%3B+Win64%3B+x64)+AppleWebKit%2F537.36+(KHTML%2C+like+Gecko)+Chrome%2F114.0.0.0+Safari%2F537.36&browserIdKey=window.browserLink.initializationData.browserId&browserId=a751-9d1c&clientProtocol=1.3&_=1689858441403' from origin 'https://localhost:44378' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

    I have tried adding the below code but still the error remains

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => options.AddPolicy("MyMyAllowCredentialsPolicy",
    policy =>
    {
        policy.WithOrigins("https://localhost:44378")
               .AllowCredentials();
    }));
    

    And

        services.AddCors(options => options.AddPolicy("AllowAll", p =>
        {
            p.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials();
        }));
    

    Finally

            services.AddCors(options => options.AddDefaultPolicy(policy =>
            {
                policy.WithOrigins("https://localhost:44378/", "'http://localhost:57127", "AllowAll")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
                .SetIsOriginAllowedToAllowWildcardSubdomains();
            }));
    

    But non seem to work.

    What needs to be done to resolve this?

  • Paul Seal 524 posts 2889 karma points MVP 6x c-trib
    Jul 21, 2023 @ 10:32
    Paul Seal
    1

    Hi

    I'm not sure of the exact implementation in v9 but I wrote a blog post on how to do it in v12.

    https://codeshare.co.uk/blog/how-to-set-up-a-cors-policy-in-umbraco-12/

    The process should be similar.

    1. Add a private variable to contain the name of the CORS policy.

    2. In the ConfigureServices method, add the Cors service:

    3. Now we need to tell it to use Cors and this is the most important part The order of where we call this really matters. It has to be called directly between .UseRouting(); and .UseAuthentication();

    So to achieve this we modify the Configure method, to give us more control.

    Here is what your Startup.cs should probably be in v9 depending on your version.

        using System;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Umbraco.Cms.Core.DependencyInjection;
    using Umbraco.Extensions;
    
    namespace Umbraco.Cms.Web.UI
    {
        public class Startup
        {
            private readonly IWebHostEnvironment _env;
            private readonly IConfiguration _config;
            private readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    
            /// <summary>
            /// Initializes a new instance of the <see cref="Startup" /> class.
            /// </summary>
            /// <param name="webHostEnvironment">The web hosting environment.</param>
            /// <param name="config">The configuration.</param>
            /// <remarks>
            /// Only a few services are possible to be injected here https://github.com/dotnet/aspnetcore/issues/9337.
            /// </remarks>
            public Startup(IWebHostEnvironment webHostEnvironment, IConfiguration config)
            {
                _env = webHostEnvironment ?? throw new ArgumentNullException(nameof(webHostEnvironment));
                _config = config ?? throw new ArgumentNullException(nameof(config));
            }
    
            /// <summary>
            /// Configures the services.
            /// </summary>
            /// <param name="services">The services.</param>
            /// <remarks>
            /// This method gets called by the runtime. Use this method to add services to the container.
            /// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940.
            /// </remarks>
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddCors(options =>
                {
                    options.AddPolicy(name: MyAllowSpecificOrigins,
                        policy  =>
                        {
                            policy.WithOrigins("https://headlesstest.localtest.me");
                        });
                });
    
                services.AddUmbraco(_env, _config)
                    .AddBackOffice()
                    .AddWebsite()
                    .AddComposers()
                    .Build();
            }
    
            /// <summary>
            /// Configures the application.
            /// </summary>
            /// <param name="app">The application builder.</param>
            /// <param name="env">The web hosting environment.</param>
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    #if (UseHttpsRedirect)
    
                app.UseHttpsRedirection();
    #endif
    
                app.UseUmbraco()
                    .WithCustomMiddleware(u =>
                    {
                        u.RunPrePipeline();
    
                        u.UseUmbracoCoreMiddleware();
    
                        // Important we handle image manipulations before the static files, otherwise the querystring is just ignored.
                        u.AppBuilder.UseImageSharp();
    
                        // Get media file provider and request path/URL
                        var mediaFileManager = u.AppBuilder.ApplicationServices.GetRequiredService<MediaFileManager>();
                        if (mediaFileManager.FileSystem.TryCreateFileProvider(out IFileProvider mediaFileProvider))
                        {
                            GlobalSettings globalSettings = u.AppBuilder.ApplicationServices.GetRequiredService<IOptions<GlobalSettings>>().Value;
                            IHostingEnvironment hostingEnvironment = u.AppBuilder.ApplicationServices.GetService<IHostingEnvironment>();
                            string mediaRequestPath = hostingEnvironment.ToAbsolute(globalSettings.UmbracoMediaPath);
    
                            // Configure custom file provider for media
                            IWebHostEnvironment webHostEnvironment = u.AppBuilder.ApplicationServices.GetService<IWebHostEnvironment>();
                            webHostEnvironment.WebRootFileProvider = webHostEnvironment.WebRootFileProvider.ConcatComposite(new PrependBasePathFileProvider(mediaRequestPath, mediaFileProvider));
                        }
    
                        u.AppBuilder.UseStaticFiles();
    
                        u.AppBuilder.UseUmbracoPluginsStaticFiles();
                        u.AppBuilder.UseRouting();
    
                        u.AppBuilder.UseCors(MyAllowSpecificOrigins);
    
                        u.AppBuilder.UseAuthentication();
                        u.AppBuilder.UseAuthorization();
    
                        // This must come after auth because the culture is based on the auth'd user
                        u.AppBuilder.UseRequestLocalization();
    
                        // Must be called after UseRouting and before UseEndpoints
                        u.AppBuilder.UseSession();      
    
                        u.RunPostPipeline();
                        u.UseBackOffice();
                        u.UseWebsite();
                    })
                    .WithEndpoints(u =>
                    {
                        u.UseInstallerEndpoints();
                        u.UseBackOfficeEndpoints();
                        u.UseWebsiteEndpoints();
                    });
            }
        }
    }
    

    Kind regards

    Paul

Please Sign in or register to post replies

Write your reply to:

Draft