1
0

TokenController.php 11 KB

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