Skip to content

feat: centralize HTTP middleware ordering - #17

Merged
PANiXiDA merged 27 commits into
mainfrom
feature/http-pipeline-authentication
Oct 10, 2026
Merged

PANiXiDA merged 27 commits into
mainfrom
feature/http-pipeline-authentication

Conversation

@PANiXiDA

@PANiXiDA PANiXiDA commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

UseHttp() включает CORS, authentication и authorization внутрь обработки исключений и логирования запроса. Ответы 401/403, CORS preflight и ошибки аутентификации получают итоговый HTTP completion-лог. Порядок: forwarded headers → request logging → exception handling → HTTPS redirection → routing → CORS → authentication → authorization → antiforgery.

AddHttp() всегда регистрирует базовые сервисы через AddAuthentication(), AddAuthorization() и AddCors(). UseHttp() безусловно подключает middleware; проверки DI и временные scope для определения сервисов удалены. Приложение по-прежнему настраивает схемы и политики. Настройки сохраняются независимо от порядка регистрации. CORS использует настроенную default- или endpoint-политику и работает до авторизации, в том числе с DI без IServiceProviderIsService.

HttpRequestLogScope создаёт обычные словари: базовые поля фиксируются в начале запроса, endpoint — после routing, пользователь (sub с fallback на NameIdentifier) — после authentication. Итоговая запись получает конечный контекст, включая endpoint из обработанного исключения. Значения scope сохраняются при отложенном экспорте. Клиентская отмена до начала ответа остаётся 499 / Warning; остальные 4xx — Warning, 5xx — Error. Обработчики исключений не дублируют completion-лог.

Путь health endpoint настраивается через HealthCheckOptions.Path, по умолчанию /health. Регистрация и маппинг вынесены в HealthChecksConfiguration. Пустой или относительный путь отклоняется при запуске; при переопределении маппится только выбранный адрес. Проверены default и custom path, ответы 200/503 и невалидные настройки.

Собственные настройки находятся в Options/Scalar и Options/HealthCheck: ScalarOptions и HealthCheckOptions, рядом — их IValidateOptions<T>-валидаторы. Проверки выполняются через ValidateOnStart(). Секция Scalar остаётся ScalarConfiguration; секция health — HealthCheckOptions. Пустые Title/Favicon сохраняют прежнее поведение, пустые имена Bearer-схем отклоняются при запуске.

MiddlewareConfiguration регистрирует exception handlers, подключает request logging перед exception handling и содержит регистрацию endpoint/user scope. LoggingMiddleware отвечает за обработку запроса и итоговый лог. UseHttp() явно подключает HTTPS redirection, routing и endpoint scope; user scope подключается после authentication в AuthenticationConfiguration. Порядок выполнения сохранён. Удалены все 23 явные проверки ArgumentNullException.ThrowIfNull и единственный ArgumentException.ThrowIfNullOrWhiteSpace; non-nullable параметры по-прежнему требуют ненулевые аргументы, отдельный контракт исключений для null больше не поддерживается. Удалены только девять тестов этих проверок.

AddHttp() напрямую вызывает AddAntiforgery(), а UseHttp() — UseAntiforgery() после authentication/authorization. JSON-запросы без antiforgery metadata продолжают работать без токена. Для [FromForm] и IFormFile требуются токен и cookie: отсутствующий или неверный токен даёт 400 / Warning. Bearer сам по себе проверку не отключает; для endpoint, использующих только Bearer, доступен .DisableAntiforgery(). Выдачу токенов и AntiforgeryOptions настраивает приложение.

Версия — 5.0. В приложении используется один UseHttp().

Проверено локально:

  • dotnet restore, dotnet format, Release-сборка без предупреждений и ошибок; анализаторы уровня Info в изменённых файлах.
  • 397 тестов без пропусков.
  • Базовые сервисы без схем/политик и сохранение настроек приложения до/после AddHttp(); OpenAPI без default authentication scheme.
  • Обычный DI и DI без introspection, CORS preflight/401/403, fallback authorization/AllowAnonymous, scoped handlers, отмены и ошибки authentication/authorization, HTTPS/ShortCircuit.
  • Стабильность route/endpoint/user при отложенном чтении scope для 200/400/499/500 и отсутствие дублирующихся полей.
  • Antiforgery: успешные и неверные токены для форм/файлов, передача через header/form, настройки до/после AddHttp(), совместимость JSON и ручного чтения form-urlencoded, OpenIddict Bearer, 401/403 до проверки токена и явный opt-out.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-10T08:53:04.478216Z 1ff42f0 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2d98bac3a8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@PANiXiDA

PANiXiDA commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

@codex

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f39e5b76a8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@PANiXiDA

Copy link
Copy Markdown
Contributor Author

@codex

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1ff42f0577

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@PANiXiDA

Copy link
Copy Markdown
Contributor Author

@codex

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 1ff42f0577

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@PANiXiDA
PANiXiDA merged commit c0d80a4 into main Oct 10, 2026
7 checks passed
@PANiXiDA
PANiXiDA deleted the feature/http-pipeline-authentication branch October 10, 2026 08:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants