CSRFTokenController.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Core\Controller;
  8. use OC\Security\CSRF\CsrfTokenManager;
  9. use OCP\AppFramework\Controller;
  10. use OCP\AppFramework\Http;
  11. use OCP\AppFramework\Http\Attribute\FrontpageRoute;
  12. use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
  13. use OCP\AppFramework\Http\Attribute\PublicPage;
  14. use OCP\AppFramework\Http\JSONResponse;
  15. use OCP\IRequest;
  16. class CSRFTokenController extends Controller {
  17. public function __construct(
  18. string $appName,
  19. IRequest $request,
  20. private CsrfTokenManager $tokenManager,
  21. ) {
  22. parent::__construct($appName, $request);
  23. }
  24. /**
  25. * Returns a new CSRF token.
  26. *
  27. * @return JSONResponse<Http::STATUS_OK, array{token: string}, array{}>|JSONResponse<Http::STATUS_FORBIDDEN, list<empty>, array{}>
  28. *
  29. * 200: CSRF token returned
  30. * 403: Strict cookie check failed
  31. */
  32. #[PublicPage]
  33. #[NoCSRFRequired]
  34. #[FrontpageRoute(verb: 'GET', url: '/csrftoken')]
  35. public function index(): JSONResponse {
  36. if (!$this->request->passesStrictCookieCheck()) {
  37. return new JSONResponse([], Http::STATUS_FORBIDDEN);
  38. }
  39. $requestToken = $this->tokenManager->getToken();
  40. return new JSONResponse([
  41. 'token' => $requestToken->getEncryptedValue(),
  42. ]);
  43. }
  44. }