【发布时间】:2019-03-27 23:50:14
【问题描述】:
问题
当应用发布到 App Engine 时,我无法让从 HTTP 到 HTTPS 的自动重定向正常工作。
当我通过 example.com 访问该网站时,该网站被路由到 http://www.example.com 并显示连接不安全。 当我通过https://www.example.com 访问该网站时,该网站将使用谷歌管理的 SSL 正确保护。但是不会发生从 HTTP 到 HTTPS 的自动重定向。
我还在日志查看器中收到错误警告,提示 Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware 正在抛出无法确定重定向的 https 端口。
我已按照 MSDN 的文档进行操作,仅在本地运行,但在应用发布到 App Engine 时无法运行。 https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-2.1&tabs=visual-studio
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseStatusCodePages();
app.UseExceptionHandler("/Error");
app.UseHsts(); // This was added by the template
}
app.UseHttpsRedirection(); // This was added by the template
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc();
}
这是 Program.cs。基本上来自项目模板的默认值
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.CaptureStartupErrors(true)
.UseStartup<Startup>();
}
用于部署的 app.yaml
runtime: aspnetcore
env: flexible
automatic_scaling:
min_num_instances: 1
max_num_instances: 20
cpu_utilization:
target_utilization: 0.8
readiness_check:
path: "/readinesscheck"
check_interval_sec: 5
timeout_sec: 4
failure_threshold: 2
success_threshold: 2
app_start_timeout_sec: 300
liveness_check:
path: "/livenesscheck"
check_interval_sec: 30
timeout_sec: 4
failure_threshold: 2
success_threshold: 2
skip_files:
- node_modules/
- wwwroot/src/vendor/
- ^(.*/)?.*\.pdb$
- ^(.*/)?.*\.log$
我尝试过的是以下(一次只有一个)
- 将HttpsRedirection 中间件添加到ConfigureServices 方法。
最终导致应用程序无法访问(502 服务器错误)。
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
options.HttpsPort = 443;
});
- 将 EnvironmentVariable 添加到 app.yaml
还导致应用无法访问(502 服务器错误)。
env_variables:
ASPNETCORE_HTTPS_PORT: "443"
- 在 Program.cs 中手动配置 HTTPS 端口
还导致应用无法访问(502 服务器错误)。
WebHost.CreateDefaultBuilder(args)
.UseSetting("https_port", "8080") // also return 502 when port is 443
- 在 ConfigureServices 方法中配置 ForwardedHeaderOptions,在 Configure 方法中使用 ForwardedHeaderOptions。 https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.1#other-proxy-server-and-load-balancer-scenarios
应用程序可以访问,但没有自动 HTTP/HTTPS 重定向。
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
app.UseForwardedHeaders();
- 在 Dockerfile 中手动公开 443 和 8080 端口。
应用程序可以访问,但没有自动 HTTP/HTTPS 重定向。我了解当 app.yaml 中的运行时设置为 aspnetcore 时。发布过程自动生成自己的 Dockerfile,用于将应用部署到 App Engine。
EXPOSE 443
EXPOSE 8080
【问题讨论】:
标签: c# asp.net google-app-engine asp.net-core google-cloud-platform