OauthApiController.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch>
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Roeland Jago Douma <roeland@famdouma.nl>
  9. *
  10. * @license GNU AGPL version 3 or any later version
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License as
  14. * published by the Free Software Foundation, either version 3 of the
  15. * License, or (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. *
  25. */
  26. namespace OCA\OAuth2\Controller;
  27. use OC\Authentication\Exceptions\ExpiredTokenException;
  28. use OC\Authentication\Exceptions\InvalidTokenException;
  29. use OC\Authentication\Token\IProvider as TokenProvider;
  30. use OC\Security\Bruteforce\Throttler;
  31. use OCA\OAuth2\Db\AccessTokenMapper;
  32. use OCA\OAuth2\Db\ClientMapper;
  33. use OCA\OAuth2\Exceptions\AccessTokenNotFoundException;
  34. use OCA\OAuth2\Exceptions\ClientNotFoundException;
  35. use OCP\AppFramework\Controller;
  36. use OCP\AppFramework\Http;
  37. use OCP\AppFramework\Http\JSONResponse;
  38. use OCP\AppFramework\Utility\ITimeFactory;
  39. use OCP\IRequest;
  40. use OCP\Security\ICrypto;
  41. use OCP\Security\ISecureRandom;
  42. class OauthApiController extends Controller {
  43. /** @var AccessTokenMapper */
  44. private $accessTokenMapper;
  45. /** @var ClientMapper */
  46. private $clientMapper;
  47. /** @var ICrypto */
  48. private $crypto;
  49. /** @var TokenProvider */
  50. private $tokenProvider;
  51. /** @var ISecureRandom */
  52. private $secureRandom;
  53. /** @var ITimeFactory */
  54. private $time;
  55. /** @var Throttler */
  56. private $throttler;
  57. public function __construct(string $appName,
  58. IRequest $request,
  59. ICrypto $crypto,
  60. AccessTokenMapper $accessTokenMapper,
  61. ClientMapper $clientMapper,
  62. TokenProvider $tokenProvider,
  63. ISecureRandom $secureRandom,
  64. ITimeFactory $time,
  65. Throttler $throttler) {
  66. parent::__construct($appName, $request);
  67. $this->crypto = $crypto;
  68. $this->accessTokenMapper = $accessTokenMapper;
  69. $this->clientMapper = $clientMapper;
  70. $this->tokenProvider = $tokenProvider;
  71. $this->secureRandom = $secureRandom;
  72. $this->time = $time;
  73. $this->throttler = $throttler;
  74. }
  75. /**
  76. * @PublicPage
  77. * @NoCSRFRequired
  78. *
  79. * @param string $grant_type
  80. * @param string $code
  81. * @param string $refresh_token
  82. * @param string $client_id
  83. * @param string $client_secret
  84. * @return JSONResponse
  85. */
  86. public function getToken($grant_type, $code, $refresh_token, $client_id, $client_secret): JSONResponse {
  87. // We only handle two types
  88. if ($grant_type !== 'authorization_code' && $grant_type !== 'refresh_token') {
  89. return new JSONResponse([
  90. 'error' => 'invalid_grant',
  91. ], Http::STATUS_BAD_REQUEST);
  92. }
  93. // We handle the initial and refresh tokens the same way
  94. if ($grant_type === 'refresh_token') {
  95. $code = $refresh_token;
  96. }
  97. try {
  98. $accessToken = $this->accessTokenMapper->getByCode($code);
  99. } catch (AccessTokenNotFoundException $e) {
  100. return new JSONResponse([
  101. 'error' => 'invalid_request',
  102. ], Http::STATUS_BAD_REQUEST);
  103. }
  104. try {
  105. $client = $this->clientMapper->getByUid($accessToken->getClientId());
  106. } catch (ClientNotFoundException $e) {
  107. return new JSONResponse([
  108. 'error' => 'invalid_request',
  109. ], Http::STATUS_BAD_REQUEST);
  110. }
  111. if (isset($this->request->server['PHP_AUTH_USER'])) {
  112. $client_id = $this->request->server['PHP_AUTH_USER'];
  113. $client_secret = $this->request->server['PHP_AUTH_PW'];
  114. }
  115. // The client id and secret must match. Else we don't provide an access token!
  116. if ($client->getClientIdentifier() !== $client_id || $client->getSecret() !== $client_secret) {
  117. return new JSONResponse([
  118. 'error' => 'invalid_client',
  119. ], Http::STATUS_BAD_REQUEST);
  120. }
  121. $decryptedToken = $this->crypto->decrypt($accessToken->getEncryptedToken(), $code);
  122. // Obtain the appToken associated
  123. try {
  124. $appToken = $this->tokenProvider->getTokenById($accessToken->getTokenId());
  125. } catch (ExpiredTokenException $e) {
  126. $appToken = $e->getToken();
  127. } catch (InvalidTokenException $e) {
  128. //We can't do anything...
  129. $this->accessTokenMapper->delete($accessToken);
  130. return new JSONResponse([
  131. 'error' => 'invalid_request',
  132. ], Http::STATUS_BAD_REQUEST);
  133. }
  134. // Rotate the apptoken (so the old one becomes invalid basically)
  135. $newToken = $this->secureRandom->generate(72, ISecureRandom::CHAR_ALPHANUMERIC);
  136. $appToken = $this->tokenProvider->rotate(
  137. $appToken,
  138. $decryptedToken,
  139. $newToken
  140. );
  141. // Expiration is in 1 hour again
  142. $appToken->setExpires($this->time->getTime() + 3600);
  143. $this->tokenProvider->updateToken($appToken);
  144. // Generate a new refresh token and encrypt the new apptoken in the DB
  145. $newCode = $this->secureRandom->generate(128, ISecureRandom::CHAR_ALPHANUMERIC);
  146. $accessToken->setHashedCode(hash('sha512', $newCode));
  147. $accessToken->setEncryptedToken($this->crypto->encrypt($newToken, $newCode));
  148. $this->accessTokenMapper->update($accessToken);
  149. $this->throttler->resetDelay($this->request->getRemoteAddress(), 'login', ['user' => $appToken->getUID()]);
  150. return new JSONResponse(
  151. [
  152. 'access_token' => $newToken,
  153. 'token_type' => 'Bearer',
  154. 'expires_in' => 3600,
  155. 'refresh_token' => $newCode,
  156. 'user_id' => $appToken->getUID(),
  157. ]
  158. );
  159. }
  160. }