/
ivanstrike
/
tasker
Обзор
Документация
Войти
/
ivanstrike
/
tasker
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Middleware/ApiKeyAuthMiddleware.cs
84 строки
3 KB
ivanstrike
Лабораторная работа 2
08 ноя 2025, 11:16
08 ноя 2025, 11:16
ec39293
Код
Авторство
О чём код?
namespace TaskerApi.Middleware; /// <summary> /// Middleware для аутентификации внутренних сервисов через API ключ /// </summary> public class ApiKeyAuthMiddleware { private readonly RequestDelegate _next; private readonly IConfiguration _configuration; private readonly ILogger<ApiKeyAuthMiddleware> _logger; private const string ApiKeyHeaderName = "X-Api-Key"; public ApiKeyAuthMiddleware( RequestDelegate next, IConfiguration configuration, ILogger<ApiKeyAuthMiddleware> logger) { _next = next; _configuration = configuration; _logger = logger; } public async Task InvokeAsync(HttpContext context) { // Проверяем только пути, начинающиеся с /api/internal if (!context.Request.Path.StartsWithSegments("/api/internal")) { await _next(context); return; } _logger.LogInformation("Internal API request to {Path}", context.Request.Path); _logger.LogDebug("Headers: {Headers}", string.Join(", ", context.Request.Headers.Select(h => $"{h.Key}={h.Value}"))); if (!context.Request.Headers.TryGetValue(ApiKeyHeaderName, out var extractedApiKey)) { _logger.LogWarning("API Key header '{HeaderName}' not found. Available headers: {Headers}", ApiKeyHeaderName, string.Join(", ", context.Request.Headers.Keys)); context.Response.StatusCode = 401; await context.Response.WriteAsJsonAsync(new { error = "API Key missing", message = $"API Key is required in {ApiKeyHeaderName} header for internal endpoints" }); return; } _logger.LogDebug("Extracted API Key: {Key}", extractedApiKey.ToString().Substring(0, Math.Min(10, extractedApiKey.ToString().Length)) + "..."); var validApiKey = _configuration["InternalApi:ApiKey"]; if (string.IsNullOrWhiteSpace(validApiKey)) { _logger.LogError("Internal API key not configured"); context.Response.StatusCode = 500; await context.Response.WriteAsJsonAsync(new { error = "Internal configuration error" }); return; } if (!string.Equals(extractedApiKey, validApiKey, StringComparison.Ordinal)) { context.Response.StatusCode = 401; await context.Response.WriteAsJsonAsync(new { error = "Invalid API Key", message = "The provided API Key is not valid" }); _logger.LogWarning("Internal API access attempt with invalid API key from {IP}", context.Connection.RemoteIpAddress); return; } _logger.LogInformation("Internal API access granted from {IP}", context.Connection.RemoteIpAddress); await _next(context); } }