Azure广告身份验证回复URL包含http而不是带有.netcore中间件的https-如何强制执行https?

问题描述

请注意http而不是https。当我将HTTP替换为https时,将被重定向并成功收到承载令牌。如何强制中间件生成的URL包含https?

中间件:

   services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
        .AddAzureAD(options => Configuration.Bind("AzureAd",options));

重定向后创建的请求:

https://login.microsoftonline.com/6957e{...}825/oauth2/authorize?
    client_id=747{...}9810&redirect_uri=http%3A%2F%2F {... continued url ...}

解决方法

根据Microsoft文档,您应该使用UseHttpsRedirection来实现此目的:

  • HTTPS重定向中间件(UseHttpsRedirection),用于将所有HTTP请求重定向到HTTPS。

ASP.NET Core Enforce HTTPS

.UseHttpsRedirection()将发出从http重定向到https的HTTP响应代码。

,

我能够用Stef Heyenrath在Stackoverflow帖子上发表的评论来解决我的问题:How to set redirect_uri protocol to HTTPS in Azure Web Apps

步骤1:配置ForwardedHeadersOptions

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.RequireHeaderSymmetry = false;
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;

    // TODO : it's a bit unsafe to allow all Networks and Proxies...
    options.KnownNetworks.Clear();
    options.KnownProxies.Clear();
});

第2步:在公共无效的Configure(IApplicationBuilder应用,

中使用UseForwardedHeaders,
IHostingEnvironment env) method

app.UseForwardedHeaders();

第3步:仅将UseHttpsRedirection用于生产

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

    // Forward http to https (only needed for local development because the Azure Linux App Service already enforces https)
    app.UseHttpsRedirection();
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}