Получение страницы была загружена через HTTPS, но запрошена небезопасная конечная точка XMLHttpRequest '.well-known / openid-configuration'

Итак, у меня есть проект ASP.Net Core Hosted Blazor Web Assembly с использованием Identity Server 4 для управления моими логинами и регистрацией, и когда я отлаживаю и пытаюсь войти в свое приложение, конечная точка '.well-known / openid- конфигурация ' обслуживается через HTTPS, но когда я запускаю опубликованную версию в Docker, она обслуживается через HTTP, и моя страница входа в систему не работает. Как я могу получить его по HTTPS?

Полная ошибка: AuthenticationService.js: 1 смешанный контент: страница https://musicfusion.app/ была загружена через HTTPS, но запросила небезопасную конечную точку XMLHttpRequest http://musicfusion.app/.well-known / openid-configuration '. Этот запрос заблокирован; контент должен обслуживаться по HTTPS.

Изменить: My Startup.cs

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Linq;
using Soundbox.Server.Data;
using Soundbox.Shared;
using System;
using Blazored.Toast;
using test.Server.Hubs;
using Microsoft.AspNetCore.Identity.UI.Services;
using test.Server.Services;
using Microsoft.AspNetCore.HttpOverrides;

namespace test.Server
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

    public IConfiguration Configuration { get; }

    // 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
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlite("Data Source=/data/test.db"));
        services.AddBlazoredToast();
        services.Configure<APIKeys>(this.Configuration.GetSection("APIKeys"));
        services.Configure<AuthMessageSenderOptions>(this.Configuration.GetSection("Emails"));
        services.Configure<ForwardedHeadersOptions>(options =>
        {
            options.ForwardedHeaders =
                ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
        });
        services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddIdentityServer()
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

        services.AddAuthentication()
            .AddIdentityServerJwt();

        //services.AddCors(options =>
        //{
        //    options.AddPolicy("AllowSpecificOrigin",
        //            builder =>
        //            {
        //                builder
        //                .AllowAnyOrigin()
        //                .AllowAnyMethod()
        //                .AllowAnyHeader();
        //            });
        //});

        services.AddControllersWithViews();

        // requires
        // using Microsoft.AspNetCore.Identity.UI.Services;
        // using WebPWrecover.Services;
        services.AddTransient<IEmailSender, EmailSender>();

        services.AddRazorPages();
        services.AddSignalR();
        services.AddResponseCompression(opts =>
        {
            opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                new[] { "application/octet-stream" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseResponseCompression();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseWebAssemblyDebugging();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseBlazorFrameworkFiles();
        app.UseStaticFiles();


        //app.UseCors("AllowSpecificOrigin");
        app.UseRouting();

        app.UseIdentityServer();
        app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
        });
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllers();
            endpoints.MapHub<PlaylistHub>("/playlisthub");
            endpoints.MapFallbackToFile("index.html");
        });

        UpdateDatabase(app);
    }

    private static void UpdateDatabase(IApplicationBuilder app)
    {
        using (var serviceScope = app.ApplicationServices
            .GetRequiredService<IServiceScopeFactory>()
            .CreateScope())
        {
            using (var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>())
            {
                context.Database.Migrate();
            }
        }
    }
}
}

person Mikerad    schedule 19.09.2020    source источник


Ответы (4)


Добавление следующей строки к startup.cs в серверном проекте, похоже, устранило проблему для меня:

app.Use((ctx, next) => { ctx.SetIdentityServerOrigin("https://www.my-domain-name-here.co.uk"); return next(); });
person Mgwd    schedule 11.11.2020

Я тоже боролся с этим. Наконец-то пришло решение. В Startup.ConfigureServices добавьте параметры IdentityServer следующим образом:

        services.AddIdentityServer(options =>
        {
            options.PublicOrigin = Configuration["PublicOrigin"];
        })

Затем поместите общедоступный источник HTTPS в свой appsettings.json (например, "PublicOrigin": "https://example.com").

person Jared    schedule 01.01.2021

Решением было заставить Cloudflare передавать весь трафик по протоколу HTTPS.

Изменить: чтобы понять это правильно, следуйте этому руководству: https://blog.cloudflare.com/how-to-make-your-site-https-only/

person Mikerad    schedule 16.01.2021
comment
Было бы здорово добавить описание того, как этого добиться, и любой необходимый код, чтобы вы помогали другим в будущем с той же проблемой. - person Ruli; 16.01.2021

Если вы используете IdentityServer4, вы можете поместить это в свой запуск:

app.Use(async (ctx, next) =>
{
    ctx.Request.Scheme = "https";
    await next();
});

Затем он заставит Identity Server использовать https для всех создаваемых им ссылок. Это очень помогло, так как я использую обратный прокси

person Carl    schedule 13.05.2021