/
Lexus_666
/
Pir_API
Обзор
Документация
Войти
/
Lexus_666
/
Pir_API
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Middleware/ApiKeyMiddleware.cs
46 строк
1 KB
Lexus_666
Lab 2 done
20 окт 2025, 05:24
20 окт 2025, 05:24
1680046
Код
Авторство
О чём код?
using Pir_API.Interfaces; namespace Pir_API.Middleware; public class ApiKeyMiddleware { private readonly RequestDelegate _next; private readonly IApiKeyService _apiKeyService; public ApiKeyMiddleware(RequestDelegate next, IApiKeyService apiKeyService) { _next = next; _apiKeyService = apiKeyService; } public async Task InvokeAsync(HttpContext context) { if (context.Request.Path.StartsWithSegments("/api/internal")) { await _next(context); return; } if (context.Request.Path.StartsWithSegments("/swagger")) { await _next(context); return; } if (!context.Request.Headers.TryGetValue("X-API-Key", out var extractedApiKey)) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; await context.Response.WriteAsync("No API key"); return; } if (!_apiKeyService.ValidateApiKey(extractedApiKey!)) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; await context.Response.WriteAsync("Wrong API Key"); return; } await _next(context); } }