TokenController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. <?php
  2. namespace OAuth2\Controller;
  3. use OAuth2\ResponseType\AccessTokenInterface;
  4. use OAuth2\ClientAssertionType\ClientAssertionTypeInterface;
  5. use OAuth2\GrantType\GrantTypeInterface;
  6. use OAuth2\ScopeInterface;
  7. use OAuth2\Scope;
  8. use OAuth2\Storage\ClientInterface;
  9. use OAuth2\RequestInterface;
  10. use OAuth2\ResponseInterface;
  11. use InvalidArgumentException;
  12. use LogicException;
  13. use RuntimeException;
  14. /**
  15. * @see TokenControllerInterface
  16. */
  17. class TokenController implements TokenControllerInterface
  18. {
  19. /**
  20. * @var AccessTokenInterface
  21. */
  22. protected $accessToken;
  23. /**
  24. * @var array<GrantTypeInterface>
  25. */
  26. protected $grantTypes;
  27. /**
  28. * @var ClientAssertionTypeInterface
  29. */
  30. protected $clientAssertionType;
  31. /**
  32. * @var ScopeInterface
  33. */
  34. protected $scopeUtil;
  35. /**
  36. * @var ClientInterface
  37. */
  38. protected $clientStorage;
  39. /**
  40. * Constructor
  41. *
  42. * @param AccessTokenInterface $accessToken
  43. * @param ClientInterface $clientStorage
  44. * @param array $grantTypes
  45. * @param ClientAssertionTypeInterface $clientAssertionType
  46. * @param ScopeInterface $scopeUtil
  47. * @throws InvalidArgumentException
  48. */
  49. public function __construct(AccessTokenInterface $accessToken, ClientInterface $clientStorage, array $grantTypes = array(), ClientAssertionTypeInterface $clientAssertionType = null, ScopeInterface $scopeUtil = null)
  50. {
  51. if (is_null($clientAssertionType)) {
  52. foreach ($grantTypes as $grantType) {
  53. if (!$grantType instanceof ClientAssertionTypeInterface) {
  54. throw new InvalidArgumentException('You must supply an instance of OAuth2\ClientAssertionType\ClientAssertionTypeInterface or only use grant types which implement OAuth2\ClientAssertionType\ClientAssertionTypeInterface');
  55. }
  56. }
  57. }
  58. $this->clientAssertionType = $clientAssertionType;
  59. $this->accessToken = $accessToken;
  60. $this->clientStorage = $clientStorage;
  61. foreach ($grantTypes as $grantType) {
  62. $this->addGrantType($grantType);
  63. }
  64. if (is_null($scopeUtil)) {
  65. $scopeUtil = new Scope();
  66. }
  67. $this->scopeUtil = $scopeUtil;
  68. }
  69. /**
  70. * Handle the token request.
  71. *
  72. * @param RequestInterface $request - Request object to grant access token
  73. * @param ResponseInterface $response - Response object
  74. */
  75. public function handleTokenRequest(RequestInterface $request, ResponseInterface $response)
  76. {
  77. if ($token = $this->grantAccessToken($request, $response)) {
  78. // @see http://tools.ietf.org/html/rfc6749#section-5.1
  79. // server MUST disable caching in headers when tokens are involved
  80. $response->setStatusCode(200);
  81. $response->addParameters($token);
  82. $response->addHttpHeaders(array(
  83. 'Cache-Control' => 'no-store',
  84. 'Pragma' => 'no-cache',
  85. 'Content-Type' => 'application/json'
  86. ));
  87. }
  88. }
  89. /**
  90. * Grant or deny a requested access token.
  91. * This would be called from the "/token" endpoint as defined in the spec.
  92. * You can call your endpoint whatever you want.
  93. *
  94. * @param RequestInterface $request - Request object to grant access token
  95. * @param ResponseInterface $response - Response object
  96. *
  97. * @return bool|null|array
  98. *
  99. * @throws \InvalidArgumentException
  100. * @throws \LogicException
  101. *
  102. * @see http://tools.ietf.org/html/rfc6749#section-4
  103. * @see http://tools.ietf.org/html/rfc6749#section-10.6
  104. * @see http://tools.ietf.org/html/rfc6749#section-4.1.3
  105. *
  106. * @ingroup oauth2_section_4
  107. */
  108. public function grantAccessToken(RequestInterface $request, ResponseInterface $response)
  109. {
  110. if (strtolower($request->server('REQUEST_METHOD')) === 'options') {
  111. $response->addHttpHeaders(array('Allow' => 'POST, OPTIONS'));
  112. return null;
  113. }
  114. if (strtolower($request->server('REQUEST_METHOD')) !== 'post') {
  115. $response->setError(405, 'invalid_request', 'The request method must be POST when requesting an access token', '#section-3.2');
  116. $response->addHttpHeaders(array('Allow' => 'POST, OPTIONS'));
  117. return null;
  118. }
  119. /**
  120. * Determine grant type from request
  121. * and validate the request for that grant type
  122. */
  123. if (!$grantTypeIdentifier = $request->request('grant_type')) {
  124. $response->setError(400, 'invalid_request', 'The grant type was not specified in the request');
  125. return null;
  126. }
  127. if (!isset($this->grantTypes[$grantTypeIdentifier])) {
  128. /* TODO: If this is an OAuth2 supported grant type that we have chosen not to implement, throw a 501 Not Implemented instead */
  129. $response->setError(400, 'unsupported_grant_type', sprintf('Grant type "%s" not supported', $grantTypeIdentifier));
  130. return null;
  131. }
  132. /** @var GrantTypeInterface $grantType */
  133. $grantType = $this->grantTypes[$grantTypeIdentifier];
  134. /**
  135. * Retrieve the client information from the request
  136. * ClientAssertionTypes allow for grant types which also assert the client data
  137. * in which case ClientAssertion is handled in the validateRequest method
  138. *
  139. * @see \OAuth2\GrantType\JWTBearer
  140. * @see \OAuth2\GrantType\ClientCredentials
  141. */
  142. if (!$grantType instanceof ClientAssertionTypeInterface) {
  143. if (!$this->clientAssertionType->validateRequest($request, $response)) {
  144. return null;
  145. }
  146. $clientId = $this->clientAssertionType->getClientId();
  147. }
  148. /**
  149. * Retrieve the grant type information from the request
  150. * The GrantTypeInterface object handles all validation
  151. * If the object is an instance of ClientAssertionTypeInterface,
  152. * That logic is handled here as well
  153. */
  154. if (!$grantType->validateRequest($request, $response)) {
  155. return null;
  156. }
  157. if ($grantType instanceof ClientAssertionTypeInterface) {
  158. $clientId = $grantType->getClientId();
  159. } else {
  160. // validate the Client ID (if applicable)
  161. if (!is_null($storedClientId = $grantType->getClientId()) && $storedClientId != $clientId) {
  162. $response->setError(400, 'invalid_grant', sprintf('%s doesn\'t exist or is invalid for the client', $grantTypeIdentifier));
  163. return null;
  164. }
  165. }
  166. /**
  167. * Validate the client can use the requested grant type
  168. */
  169. if (!$this->clientStorage->checkRestrictedGrantType($clientId, $grantTypeIdentifier)) {
  170. $response->setError(400, 'unauthorized_client', 'The grant type is unauthorized for this client_id');
  171. return false;
  172. }
  173. /**
  174. * Validate the scope of the token
  175. *
  176. * requestedScope - the scope specified in the token request
  177. * availableScope - the scope associated with the grant type
  178. * ex: in the case of the "Authorization Code" grant type,
  179. * the scope is specified in the authorize request
  180. *
  181. * @see http://tools.ietf.org/html/rfc6749#section-3.3
  182. */
  183. $requestedScope = $this->scopeUtil->getScopeFromRequest($request);
  184. $availableScope = $grantType->getScope();
  185. if ($requestedScope) {
  186. // validate the requested scope
  187. if ($availableScope) {
  188. if (!$this->scopeUtil->checkScope($requestedScope, $availableScope)) {
  189. $response->setError(400, 'invalid_scope', 'The scope requested is invalid for this request');
  190. return null;
  191. }
  192. } else {
  193. // validate the client has access to this scope
  194. if ($clientScope = $this->clientStorage->getClientScope($clientId)) {
  195. if (!$this->scopeUtil->checkScope($requestedScope, $clientScope)) {
  196. $response->setError(400, 'invalid_scope', 'The scope requested is invalid for this client');
  197. return false;
  198. }
  199. } elseif (!$this->scopeUtil->scopeExists($requestedScope)) {
  200. $response->setError(400, 'invalid_scope', 'An unsupported scope was requested');
  201. return null;
  202. }
  203. }
  204. } elseif ($availableScope) {
  205. // use the scope associated with this grant type
  206. $requestedScope = $availableScope;
  207. } else {
  208. // use a globally-defined default scope
  209. $defaultScope = $this->scopeUtil->getDefaultScope($clientId);
  210. // "false" means default scopes are not allowed
  211. if (false === $defaultScope) {
  212. $response->setError(400, 'invalid_scope', 'This application requires you specify a scope parameter');
  213. return null;
  214. }
  215. $requestedScope = $defaultScope;
  216. }
  217. return $grantType->createAccessToken($this->accessToken, $clientId, $grantType->getUserId(), $requestedScope);
  218. }
  219. /**
  220. * Add grant type
  221. *
  222. * @param GrantTypeInterface $grantType - the grant type to add for the specified identifier
  223. * @param string|null $identifier - a string passed in as "grant_type" in the response that will call this grantType
  224. */
  225. public function addGrantType(GrantTypeInterface $grantType, $identifier = null)
  226. {
  227. if (is_null($identifier) || is_numeric($identifier)) {
  228. $identifier = $grantType->getQueryStringIdentifier();
  229. }
  230. $this->grantTypes[$identifier] = $grantType;
  231. }
  232. /**
  233. * @param RequestInterface $request
  234. * @param ResponseInterface $response
  235. */
  236. public function handleRevokeRequest(RequestInterface $request, ResponseInterface $response)
  237. {
  238. if ($this->revokeToken($request, $response)) {
  239. $response->setStatusCode(200);
  240. $response->addParameters(array('revoked' => true));
  241. }
  242. }
  243. /**
  244. * Revoke a refresh or access token. Returns true on success and when tokens are invalid
  245. *
  246. * Note: invalid tokens do not cause an error response since the client
  247. * cannot handle such an error in a reasonable way. Moreover, the
  248. * purpose of the revocation request, invalidating the particular token,
  249. * is already achieved.
  250. *
  251. * @param RequestInterface $request
  252. * @param ResponseInterface $response
  253. * @throws RuntimeException
  254. * @return bool|null
  255. */
  256. public function revokeToken(RequestInterface $request, ResponseInterface $response)
  257. {
  258. if (strtolower($request->server('REQUEST_METHOD')) === 'options') {
  259. $response->addHttpHeaders(array('Allow' => 'POST, OPTIONS'));
  260. return null;
  261. }
  262. if (strtolower($request->server('REQUEST_METHOD')) !== 'post') {
  263. $response->setError(405, 'invalid_request', 'The request method must be POST when revoking an access token', '#section-3.2');
  264. $response->addHttpHeaders(array('Allow' => 'POST, OPTIONS'));
  265. return null;
  266. }
  267. $token_type_hint = $request->request('token_type_hint');
  268. if (!in_array($token_type_hint, array(null, 'access_token', 'refresh_token'), true)) {
  269. $response->setError(400, 'invalid_request', 'Token type hint must be either \'access_token\' or \'refresh_token\'');
  270. return null;
  271. }
  272. $token = $request->request('token');
  273. if ($token === null) {
  274. $response->setError(400, 'invalid_request', 'Missing token parameter to revoke');
  275. return null;
  276. }
  277. // @todo remove this check for v2.0
  278. if (!method_exists($this->accessToken, 'revokeToken')) {
  279. $class = get_class($this->accessToken);
  280. throw new RuntimeException("AccessToken {$class} does not implement required revokeToken method");
  281. }
  282. $this->accessToken->revokeToken($token, $token_type_hint);
  283. return true;
  284. }
  285. }