AuthenticateAgentService.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. <?php
  2. namespace App\Http\Middleware\V3;
  3. use App\Services\V3\AgentTraceService;
  4. use Closure;
  5. use Illuminate\Auth\AuthenticationException;
  6. use Illuminate\Http\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. /**
  9. * v3 服务间鉴权:只放行 AI 对话服务(agent-poc backend)。
  10. *
  11. * 请求头 `X-Agent-Service-Key` 与 config('mint.app.agent_service_key')(.env 的
  12. * AGENT_SERVICE_KEY)比对。密钥没配时一律拒绝,不会因为两边都是空串而放行。
  13. *
  14. * 它只证明「这是 agent 服务」;终端用户是谁另由 bearer(agent 透传的用户 token)
  15. * 决定,见 {@see AgentTraceService::record()}。
  16. *
  17. * 别名 `auth.agent-service`(在 bootstrap/app.php 注册)。
  18. */
  19. class AuthenticateAgentService
  20. {
  21. public const HEADER = 'X-Agent-Service-Key';
  22. /**
  23. * @throws AuthenticationException 密钥缺失或不匹配
  24. */
  25. public function handle(Request $request, Closure $next): Response
  26. {
  27. $expected = (string) config('mint.app.agent_service_key');
  28. $given = (string) $request->header(self::HEADER, '');
  29. if ($expected === '' || $given === '' || ! hash_equals($expected, $given)) {
  30. throw new AuthenticationException;
  31. }
  32. return $next($request);
  33. }
  34. }