failed to determine the https port for redirect
Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3] Failed to determine the https port for redirect. #18594
Comments
xshiiiidev commented Jan 27, 2020 •
Describe the bug
I am getting this error on my production server after accessing the website for the first time after deploying this error will show
Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3] Failed to determine the https port for redirect.
I am not getting this error on my kestrel web server on development.
BTW my production server is
NginX
Ubuntu18.04
Visual Studio Version: 2019 16.4.3
Dotnet Info on production server:
Host (useful for support):
Version: 3.1.1
Commit: a1388f194c
.NET Core SDKs installed:
No SDKs were found.
.NET Core runtimes installed:
Microsoft.AspNetCore.App 3.1.1 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 3.1.1 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
Copy the published files to the server
The text was updated successfully, but these errors were encountered:
We are unable to convert the task to an issue at this time. Please try again.
The issue was successfully created but we are unable to update the comment at this time.
blowdart commented Jan 27, 2020
Do you have the site configured with an HTTPS certificate? Can you share your program.cs?
Tratcher commented Jan 27, 2020
NginX is terminating your TLS in a separate process and forwarding to Kestrel without TLS, correct? In that case the https redirect middleware can’t detect at startup which port your nginx TLS is listening on. Locally when you run Kestrel directly it has its own TLS and the middleware can detect the port.
xshiiiidev commented Jan 28, 2020 •
Do you have the site configured with an HTTPS certificate? Can you share your program.cs?
from the default project creation of the ASP.NET Core MVC. I did not changed anything from the template.
NginX is terminating your TLS in a separate process and forwarding to Kestrel without TLS, correct? In that case the https redirect middleware can’t detect at startup which port your nginx TLS is listening on. Locally when you run Kestrel directly it has its own TLS and the middleware can detect the port.
I tested this and the error was gone on my app service.
The problem now is when I visit my website I cant reach it and this error shows.
I already cleared the cookies and the same thing happened.
This is my appsettings.json
xshiiiidev commented Jan 28, 2020 •
As per this document
I disabled my UseHttpsRedirection middleware
Because I already handled the https redirection in my nginx server.
The warning goes away now.
jkotalik commented Jan 29, 2020
I don’t think you should be setting the port at all. If Nginx is doing TLS termination, every time your site gets a url, it will be on HTTP. The HttpsMiddleware will notice that it is HTTP and because a port is now set, it will redirect. This will constantly happen until the browser notices you have too many redirects, which is the behavior you are seeing. I’d remove the HTTPS_PORT and/or the HttpsRedirection middleware if you know your application is deployed where TLS termination is done.
It depends on if you are concerned about the communication between nginx and kestrel using HTTP instead of HTTPS. That is based on your configuration. If it’s only on a single machine (localhost), then you should be okay.
TheCodeBuzz
Best Practices for Software Development
Resolved:Failed to determine the HTTPS port for the redirect
Resolving Failed to determine the HTTPS port for the redirect
In this article, we shall see guidelines to resolve the error “Failed to determine the HTTPS port for the redirect” while configuring the HTTP Strict Transport Security (HSTS) header in your website or API.
Issue Description
ASP.NET Core API or Website runtime gives below error,
Failed to determine the HTTPS port for the redirect
Resolution
This issue generally occurs when configuring the HTTP Strict Transport Security (HSTS) header in the website or API. The use of HSTS means all requests will be routed to HTTPS. Also, ability to re-direct insecure requests(HTTP) to secure HTTPS.
Below is sample code,
Above we have used middleware UseHttpsRedirection which redirects any HTTP request to a secured HTTPS request.
While redirecting it’s important that the port is available to redirect the request. This can be achieved by setting the variable port using any of the approaches discussed. All the below approaches ultimately sets the environment variable ASPNETCORE_HTTPS_PORT.
Approach 1
Set the environment variable ASPNETCORE_HTTPS_PORT explicitly with the port number.
Approach 2
Using apsettings.json , please add key value as “https_port”: 443
Approach 3
HTTPS port can also be set by using AddHttpsRedirection middleware option as below,
Approach 4
To set the port number for https_port use configuration or call UseSetting by using Generic Host Builder
If the reverse proxy already handles HTTPS redirection, then don’t use HTTPS Redirection Middleware.
References :
Did I miss anything else in these resolution steps?
Did the above steps resolve your issue? Please sound off your comments below!
HttpsRedirectionMiddleware will not redirect to HTTPS if no port is available #6011
Comments
jkotalik commented May 14, 2018
The text was updated successfully, but these errors were encountered:
We are unable to convert the task to an issue at this time. Please try again.
The issue was successfully created but we are unable to update the comment at this time.
guardrex commented Jun 1, 2018
we will now not redirect to HTTPS if no port is available
If the HttpsPort is not set, we will try to get the HttpsPort from the following:
Are the API comments in need of an update?
Tratcher commented Jun 1, 2018 •
Indeed, step 3 was removed as it caused problems when HTTPS was not available.
guardrex commented Jun 1, 2018
If no port is set, the request isn’t redirected. To specify an HTTPS port:
Tratcher commented Jun 1, 2018
Set an HTTPS URL for the browser to launch in launchsettings.json (Visual Studio/command line) or launch.json (Visual Studio Code).
Careful with that one. It’s more about setting an HTTPS URL to start the server on. Launching the browser is incidental.
guardrex commented Jun 1, 2018 •
I’m still having trouble groking the behavior. I add the middleware to a vanilla RP app, and the app redirects to 5001 when I didn’t explicitly set the port. That doesn’t jive with «If no port is set, the request isn’t redirected.»
guardrex commented Jun 1, 2018 •
Tratcher commented Jun 1, 2018
I think you’re overlooking the discovery steps, and the fact that VS can set it for you.
guardrex commented Jun 1, 2018
I’m in VSC, which I didn’t think was setting it. I thought the discovery step is IServerAddressesFeature in this case.
jayoma commented Aug 27, 2018
There is conflicting info here and in the docs for the name of the environment variable: ASPNETCORE_HTTPS_PORT vs HTTPS_PORT.
The source for HttpsRedirectionMiddleware.TryGetHttpsPort() confirms that it’s looking for the HTTPS_PORT variable.
To be safe, I’ve added both environment variables to the server with the value 443. After deploying a new ASP.NET Core 2.1 app (running behind IIS 8), I started seeing the following in the logs, and the https redirect is hit or miss:
Failed to determine the https port for redirect.
How can I determine why the redirect is working for some requests, but not others? Also, since Kestrel is running on a seemingly randomly-assigned localhost port behind IIS, where exactly is the https 443 redirect supposed to apply? To Kestrel or to IIS? IIS seems like the obvious answer here, but since I don’t fully understand the concept of IIS acting as a reverse proxy for Kestrel, figured it wouldn’t hurt to ask.
jkotalik commented Aug 28, 2018
ASPNETCORE_HTTPS_PORT vs HTTPS_PORT.
Specifically: «The prefix is stripped off when the configuration key-value pairs are created.» So you should only need to set ASPNETCORE_HTTPS_PORT. The HttpsRedirectionMiddleware looks for HTTPS_PORT because the ASPNETCORE_ prefix has already been stripped off as configuration kvp have been created.
After deploying a new ASP.NET Core 2.1 app (running behind IIS 8), I started seeing the following in the logs, and the https redirect is hit or miss.
This one seems interesting. @javiercn @Tratcher can you remind me of what the flow is when HTTPS is enabled for ANCM+Kestrel? The flakiness could be an issue though. Are you sending the same request multiple times and seeing different results?
javiercn commented Aug 28, 2018
I don’t know how it can be either flacky or wrong. HTTPS_PORT will win over ASPNETCORE_HTTPS_PORT but both should be available when Kestrel is being configured, so no idea why the middleware is producing that log entry.
I’m more inclined to think there’s an issue in the config of IIS than anything else.
javiercn commented Aug 28, 2018
@jayoma Thanks for contacting us. This is a discussion issue. If you are experiencing problems please file a separate issue in the appropriate repo (Home) and we’ll follow up there.
Tratcher commented Aug 28, 2018
Note that the error is only logged once on the first request. You shouldn’t get different behavior per request unless they somehow mess up their x-forwarded-proto headers.
jayoma commented Aug 28, 2018
Thanks for the replies. I’ll look into this a bit more tomorrow with my particular setup, and see if I can provide better insight.
I’m more inclined to think there’s an issue in the config of IIS than anything else.
I’m intrigued by this comment; while I’m not terribly familiar with the ins and outs of our IIS configuration as a whole, this website was a pretty standard setup.
Note that the error is only logged once on the first request.
Also great to know. I was wondering why it only logged the warning once.
Tratcher commented Aug 28, 2018
Clarification: Where do you set ASPNETCORE_HTTPS_PORT? IIS runs as a different user and won’t pick up your user environment variables. If you changed system env vars you’d have to restart IIS.
jayoma commented Aug 30, 2018
If you changed system env vars you’d have to restart IIS.
Yes, it was set on the system env vars, and we did actually think to restart IIS, but thanks for confirming that was needed. I haven’t had a chance yet to look into this further, but will update here as soon as I’m able to.
jayoma commented Sep 5, 2018
Kurira commented Oct 22, 2018
Specifically: «The prefix is stripped off when the configuration key-value pairs are created.» So you should only need to set ASPNETCORE_HTTPS_PORT. The HttpsRedirectionMiddleware looks for HTTPS_PORT because the ASPNETCORE_ prefix has already been stripped off as configuration kvp have been created.
Tratcher commented Oct 22, 2018
punppis commented Jan 8, 2019
HTTP: 5000
HTTPS: 5001
On localhost, redirect works correctly from HTTP 5000 to HTTPS 5001. But on linux server the server redirects to HTTPS 5000 (tries to redirect to HTTP port with HTTPS).
I have set port using
and also I have checked that HTTPS_PORT env var is set to 5001 also, but still redirects to wrong port, but only on linux server.
aspnet-hello commented Mar 11, 2019
We periodically close ‘discussion’ issues that have not been updated in a long period of time.
We apologize if this causes any inconvenience. We ask that if you are still encountering an issue, please log a new issue with updated information and we will investigate.
Middleware: HTTPS Redirection Middleware throws exception on ambiguous HTTPS ports
In ASP.NET Core 6.0, the HTTPS Redirection Middleware throws an exception of type InvalidOperationException when it finds multiple HTTPS ports in the server configuration. The exception’s message contains the text «Cannot determine the https port from IServerAddressesFeature, multiple values were found. Set the desired port explicitly on HttpsRedirectionOptions.HttpsPort.»
For discussion, see GitHub issue dotnet/aspnetcore#29222.
Version introduced
Old behavior
When the HTTPS Redirection Middleware isn’t explicitly configured with a port, it searches IServerAddressesFeature during the first request to determine the HTTPS port to which it should redirect.
If there are no HTTPS ports or multiple distinct ports, it’s unclear which port should be used. The middleware logs a warning and disables itself. HTTP requests are processed normally.
New behavior
When the HTTPS Redirection Middleware isn’t explicitly configured with a port, it searches IServerAddressesFeature during the first request to determine the HTTPS port to which it should redirect.
If there are no HTTPS ports, the middleware still logs a warning and disables itself. HTTP requests are processed normally. This behavior supports:
If there are multiple distinct ports, it’s unclear which port should be used. The middleware throws an exception and fails the HTTP request.
Reason for change
This change prevents potentially sensitive data from being served over unencrypted HTTP connections when HTTPS is known to be available.
Recommended action
To enable HTTPS redirection when the server has multiple distinct HTTPS ports, you must specify one port in the configuration. For more information, see Port configuration.
If you don’t need the HTTPS Redirection Middleware in your app, remove UseHttpsRedirection from Startup.cs.
If you need to select the correct HTTPS port dynamically, provide feedback in GitHub issue dotnet/aspnetcore#21291.
Принудительное применение HTTPS в ASP.NET Core
Автор: Рик Андерсон (Rick Anderson)
В этом документе показано, как:
Ни один API не может предотвратить отправку конфиденциальных данных клиентом при первом запросе.
Проекты API
Не используйте Рекуирехттпсаттрибуте в веб-API, которые получают конфиденциальную информацию. RequireHttpsAttribute использует коды состояния HTTP для перенаправления браузеров из HTTP в HTTPS. Клиенты API могут не распознать или соблюдать перенаправления от HTTP к HTTPS. Такие клиенты могут передавать данные по протоколу HTTP. Веб-API должны быть:
Проекты HSTS и API
Проекты API
Не используйте Рекуирехттпсаттрибуте в веб-API, которые получают конфиденциальную информацию. RequireHttpsAttribute использует коды состояния HTTP для перенаправления браузеров из HTTP в HTTPS. Клиенты API могут не распознать или соблюдать перенаправления от HTTP к HTTPS. Такие клиенты могут передавать данные по протоколу HTTP. Веб-API должны быть:
Требование использовать HTTPS
в рабочей ASP.NET Core веб-приложений рекомендуется использовать:
Приложения, развернутые в конфигурации обратных прокси-серверов, позволяют прокси-серверу управлять безопасностью подключения (HTTPS). Если прокси-сервер также обрабатывает перенаправление HTTPS, нет необходимости использовать по промежуточного слоя перенаправления HTTPS. Если прокси-сервер также обрабатывает запись заголовков HSTS (например, поддержка собственного HSTS в IIS 10,0 (1709) или более поздней версии), по промежуточного слоя HSTS не требуется для приложения. Дополнительные сведения см. в разделе отказ от HTTPS/HSTS при создании проекта.
усехттпсредиректион
Следующий код вызывает UseHttpsRedirection в Startup классе:
Предыдущий выделенный код:
Конфигурация порта
Порт должен быть доступен для промежуточного слоя, чтобы перенаправить незащищенный запрос на HTTPS. Если порт недоступен:
Укажите HTTPS порт, используя любой из следующих подходов:
В конфигурации узла.
Путем задания ASPNETCORE_HTTPS_PORT переменной среды.
Путем добавления записи верхнего уровня в appsettings.json :
В конфигурации узла.
Путем задания ASPNETCORE_HTTPS_PORT переменной среды.
Путем добавления записи верхнего уровня в appsettings.json :
В среде разработки задайте URL-адрес HTTPS в launchsettings.json. при использовании IIS Express включите протокол HTTPS.
Если приложение запускается в конфигурации обратного прокси-сервера, оно IServerAddressesFeature недоступно. Задайте порт с помощью одного из других подходов, описанных в этом разделе.
Развертывания Edge
Если Kestrel или HTTP.sys используется в качестве общедоступного пограничной сервера, Kestrel или HTTP.sys должны быть настроены для прослушивания обоих типов:
Клиент должен получить доступ к незащищенному порту, чтобы приложение получило незащищенный запрос и перенаправлять клиент на безопасный порт.
Сценарии развертывания
Все брандмауэры между клиентом и сервером также должны иметь открытые порты связи для трафика.
Варианты
Следующий выделенный код вызывает аддхттпсредиректион для настройки параметров промежуточного слоя:
Предыдущий выделенный код:
Настройка постоянных перенаправлений в рабочей среде
По промежуточного слоя по умолчанию отправляется Status307TemporaryRedirect со всеми перенаправлениями. Если вы предпочитаете отправить код состояния с постоянным перенаправлением, когда приложение находится в среде, не являющейся средой разработки, заключите конфигурацию параметров по промежуточного слоя в условную проверку для среды без разработки.
При настройке служб в Startup. CS:
При настройке служб в Startup. CS:
Альтернативный подход по промежуточного слоя перенаправления HTTPS
Альтернативой по промежуточного слоя перенаправления HTTPS ( UseHttpsRedirection ) является использование по промежуточного слоя переписывания URL-адресов ( AddRedirectToHttps ). AddRedirectToHttps также может задавать код состояния и порт при выполнении перенаправления. Дополнительные сведения см. в разделе по промежуточного слоя перезаписи URL-адресов.
При перенаправлении по протоколу HTTPS без требования дополнительных правил перенаправления рекомендуется использовать по промежуточного слоя перенаправления HTTPS ( UseHttpsRedirection ), описанные в этом разделе.
Протокол HTTPS протокола безопасности транспорта HTTP (HSTS)
В OWASP, обеспечение безопасности транспорта по протоколу HTTP (HSTS) является расширением безопасности, которое определяется веб-приложением с помощью заголовка ответа. Когда браузер, поддерживающий HSTS, получает этот заголовок:
Так как HSTS применяется клиентом, у него есть некоторые ограничения.
ASP.NET Core 2,1 и более поздних версий реализует HSTS с помощью UseHsts метода расширения. Следующий код вызывает, UseHsts когда приложение не находится в режиме разработки:
UseHsts не рекомендуется в разработке, так как параметры HSTS очень кэшируются браузерами. По умолчанию UseHsts исключает локальный петлевой адрес.
Для рабочих сред, которые реализуют протокол HTTPS в первый раз, задайте для свойства Initial хстсоптионс. MaxAge небольшое значение с помощью одного из TimeSpan методов. Задайте в качестве значения в часах не более одного дня на случай, если необходимо вернуть инфраструктуру HTTPS к протоколу HTTP. Убедившись в устойчивости конфигурации HTTPS, увеличьте значение HSTS. max-age часто используемое значение — один год.
Приведенный ниже код:
UseHsts исключает следующие узлы замыкания на себя:
Отказ от HTTPS/HSTS при создании проекта
Чтобы отказаться от HTTPS/HSTS:
доверять ASP.NET Core сертификату разработки HTTPS на Windows и macOS
Сведения о браузере Firefox см. в следующем разделе.
Доверять HTTPS сертификату с помощью Firefox, чтобы предотвратить SEC_ERROR_INADEQUATE_KEY_USAGE ошибку
браузер Firefox использует собственное хранилище сертификатов и, таким образом, не доверяет сертификатам IIS Express или Kestrel разработчиков.
Существует два подхода к доверенности HTTPS-сертификата с помощью Firefox, создание файла политики или Настройка с помощью браузера FireFox. При настройке с помощью браузера создается файл политики, поэтому два подхода эквивалентны.
Создание файла политики для доверия HTTPS-сертификата с помощью Firefox
Создайте файл политики в:
Добавьте следующий код JSON в файл политики Firefox:
предыдущий файл политики позволяет браузеру Firefox доверять сертификатам из доверенных сертификатов в хранилище сертификатов Windows. В следующем разделе приводится альтернативный подход к созданию предыдущего файла политики с помощью браузера Firefox.
Настройка доверия HTTPS Certificate с помощью браузера Firefox
Задайте security.enterprise_roots.enabled = true с помощью следующих инструкций:
Как настроить сертификат разработчика для DOCKER
Ubuntu доверяет сертификату для обмена данными между службами
Установите OpenSSL 1.1.1 h или более поздней версии. Инструкции по обновлению OpenSSL см. в разделе распространение.
Выполните следующие команды:
Путь в предыдущей команде относится только к Ubuntu. Для других дистрибутивов выберите подходящий путь или используйте путь для центров сертификации (ЦС).
Доверенный HTTPS сертификат в Linux
Установка отношения доверия зависит от конкретного браузера. в следующих разделах приводятся инструкции для Chromium браузеров, а также Chrome и Firefox.
Доверенный HTTPS сертификат в Linux с использованием ребра или Chrome
Для браузеров Chromium в Linux:
Установите libnss3-tools для дистрибутива.
Экспортируйте сертификат с помощью следующей команды:
Путь в предыдущей команде относится только к Ubuntu. Для других дистрибутивов выберите подходящий путь или используйте путь для центров сертификации (ЦС). Возможно, вам потребуются повышенные разрешения для экспорта сертификата в ca-certificates папку.
Выполните следующие команды:
Закройте и перезапустите браузер.
Доверие к сертификату с помощью Firefox в Linux
Экспортируйте сертификат с помощью следующей команды:
Путь в предыдущей команде относится только к Ubuntu. Для других дистрибутивов выберите подходящий путь или используйте путь для центров сертификации (ЦС).
Создайте JSON-файл /usr/lib/firefox/distribution/policies.json со следующим содержимым:
Альтернативный способ настройки файла политики в браузере см. в статье Настройка доверия HTTPS Certificate с помощью браузера Firefox в этом документе.
Доверять сертификату с помощью Fedora 34
Доверять сертификату с другими дистрибутивов
сертификат доверия HTTPS от подсистема Windows для Linux
подсистема Windows для Linux (WSL) создает самозаверяющий сертификат разработки HTTPS. чтобы настроить Windows хранилище сертификатов для отношения доверия с сертификатом WSL:
Экспортируйте сертификат разработчика в файл на Windows:
В окне WSL импортируйте экспортированный сертификат в экземпляре WSL:
Предыдущий подход — одна операция времени для сертификата и для каждого WSL распределения. Проще экспортировать сертификат. При обновлении или повторном создании сертификата в Windows может потребоваться еще раз выполнить предыдущие команды.
Устранение неполадок с сертификатами, таких как ненадежный сертификат
Все платформы — сертификат не является доверенным
Выполните следующие команды:
Закройте все открытые экземпляры браузера. Откройте новое окно браузера для приложения. Доверие сертификатов кэшируется браузерами.
DotNet dev-certs HTTPS—сбой очистки
Предыдущие команды решают большинство проблем с доверием к браузеру. Если браузер по-прежнему не доверяет сертификату, следуйте приведенным ниже рекомендациям для конкретной платформы.
DOCKER — сертификат не является доверенным
Windows — сертификат не является доверенным
Закройте все открытые экземпляры браузера. Откройте новое окно браузера для приложения.
OS X — сертификат не является доверенным
Закройте все открытые экземпляры браузера. Откройте новое окно браузера для приложения.
IIS Express SSL-сертификат, используемый с Visual Studio
чтобы устранить проблемы с сертификатом IIS Express, выберите восстановление из установщика Visual Studio. Дополнительные сведения см. в этой статье об ошибке на GitHub.





