/
Kovalenko
/
TODO
Обзор
Документация
Войти
/
Kovalenko
/
TODO
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
lab3
TaskApi/Middleware/InternalApiKeyMiddleware.cs
50 строк
2 KB
Kovalenko1
that's all
10 янв 2026, 10:20
10 янв 2026, 10:20
4c1ccf3
Код
Авторство
О чём код?
using Microsoft.Extensions.Options; namespace TaskApi.Middleware; public class InternalApiOptions { public string ApiKey { get; init; } = string.Empty; public string HeaderName { get; init; } = "X-Internal-Api-Key"; } public class InternalApiKeyMiddleware { private readonly RequestDelegate _next; private readonly InternalApiOptions _options; public InternalApiKeyMiddleware(RequestDelegate next, IOptions<InternalApiOptions> options) { _next = next; _options = options.Value; } public async Task InvokeAsync(HttpContext context) { if (!context.Request.Path.StartsWithSegments("/internal", StringComparison.OrdinalIgnoreCase)) { await _next(context); return; } if (string.IsNullOrWhiteSpace(_options.ApiKey)) { context.Response.StatusCode = StatusCodes.Status500InternalServerError; await context.Response.WriteAsync("Internal API key is not configured."); return; } var headerName = string.IsNullOrWhiteSpace(_options.HeaderName) ? "X-Internal-Api-Key" : _options.HeaderName; if (!context.Request.Headers.TryGetValue(headerName, out var provided) || !string.Equals(provided.ToString(), _options.ApiKey, StringComparison.Ordinal)) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; await context.Response.WriteAsync("Invalid internal API key."); return; } await _next(context); } }