Authenticate.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Http\Middleware\V3;
  3. use App\Services\AuthService;
  4. use Closure;
  5. use Illuminate\Auth\AuthenticationException;
  6. use Illuminate\Http\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. /**
  9. * v3 的登录闸:没带有效 bearer token 就在进控制器之前 401。
  10. *
  11. * 挂法见 routes/v3/*.php,别名 `auth.v3`(在 bootstrap/app.php 注册)。
  12. * 可以挂在路由组上,也可以按方法挂:
  13. *
  14. * Route::apiResource('channels', ChannelController::class)
  15. * ->middlewareFor(['store', 'update', 'destroy'], 'auth.v3');
  16. *
  17. * **鉴权和 URL 形状是两件事**:要让某些动作需要登录,挂中间件就行,
  18. * 不需要把它们塞进 `/v3/me/` 前缀。
  19. *
  20. * 两个设计点:
  21. *
  22. * 1. **只认 bearer。** `AuthService::current()` 拿不到 bearer 时会回落去读
  23. * `$_COOKIE['user_uid']`,那是 v2 的旁路;v3 硬规范要求统一 bearer,所以这里
  24. * 先自己挡一道。不改 `AuthService`——它是 v2 也在用的共享代码。
  25. * 2. **解出来的用户存进 request attributes**,控制器直接取,不必再解一次 JWT。
  26. */
  27. class Authenticate
  28. {
  29. /**
  30. * 解析出的用户存在 request attributes 的哪个键下。
  31. */
  32. public const USER = 'v3.user';
  33. /**
  34. * @throws AuthenticationException 没带 bearer,或 token 无效 / 过期
  35. */
  36. public function handle(Request $request, Closure $next): Response
  37. {
  38. // 不给 AuthenticationException 传消息:bootstrap/app.php 的处理器只按状态码
  39. // 渲染,detail 留空,面向人的文案就是 Problem 的 title(RFC 9457 要求它稳定)
  40. if (! $request->bearerToken()) {
  41. throw new AuthenticationException;
  42. }
  43. $user = AuthService::current($request);
  44. if (! $user) {
  45. throw new AuthenticationException;
  46. }
  47. $request->attributes->set(self::USER, $user);
  48. return $next($request);
  49. }
  50. }