AuthorizeController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. <?php
  2. namespace OAuth2\Controller;
  3. use OAuth2\Storage\ClientInterface;
  4. use OAuth2\ScopeInterface;
  5. use OAuth2\RequestInterface;
  6. use OAuth2\ResponseInterface;
  7. use OAuth2\Scope;
  8. /**
  9. * @see OAuth2\Controller\AuthorizeControllerInterface
  10. */
  11. class AuthorizeController implements AuthorizeControllerInterface
  12. {
  13. private $scope;
  14. private $state;
  15. private $client_id;
  16. private $redirect_uri;
  17. private $response_type;
  18. protected $clientStorage;
  19. protected $responseTypes;
  20. protected $config;
  21. protected $scopeUtil;
  22. /**
  23. * @param OAuth2\Storage\ClientInterface $clientStorage REQUIRED Instance of OAuth2\Storage\ClientInterface to retrieve client information
  24. * @param array $responseTypes OPTIONAL Array of OAuth2\ResponseType\ResponseTypeInterface objects. Valid array
  25. * keys are "code" and "token"
  26. * @param array $config OPTIONAL Configuration options for the server
  27. * <code>
  28. * $config = array(
  29. * 'allow_implicit' => false, // if the controller should allow the "implicit" grant type
  30. * 'enforce_state' => true // if the controller should require the "state" parameter
  31. * 'require_exact_redirect_uri' => true, // if the controller should require an exact match on the "redirect_uri" parameter
  32. * 'redirect_status_code' => 302, // HTTP status code to use for redirect responses
  33. * );
  34. * </code>
  35. * @param OAuth2\ScopeInterface $scopeUtil OPTIONAL Instance of OAuth2\ScopeInterface to validate the requested scope
  36. */
  37. public function __construct(ClientInterface $clientStorage, array $responseTypes = array(), array $config = array(), ScopeInterface $scopeUtil = null)
  38. {
  39. $this->clientStorage = $clientStorage;
  40. $this->responseTypes = $responseTypes;
  41. $this->config = array_merge(array(
  42. 'allow_implicit' => false,
  43. 'enforce_state' => true,
  44. 'require_exact_redirect_uri' => true,
  45. 'redirect_status_code' => 302,
  46. ), $config);
  47. if (is_null($scopeUtil)) {
  48. $scopeUtil = new Scope();
  49. }
  50. $this->scopeUtil = $scopeUtil;
  51. }
  52. public function handleAuthorizeRequest(RequestInterface $request, ResponseInterface $response, $is_authorized, $user_id = null)
  53. {
  54. if (!is_bool($is_authorized)) {
  55. throw new \InvalidArgumentException('Argument "is_authorized" must be a boolean. This method must know if the user has granted access to the client.');
  56. }
  57. // We repeat this, because we need to re-validate. The request could be POSTed
  58. // by a 3rd-party (because we are not internally enforcing NONCEs, etc)
  59. if (!$this->validateAuthorizeRequest($request, $response)) {
  60. return;
  61. }
  62. // If no redirect_uri is passed in the request, use client's registered one
  63. if (empty($this->redirect_uri)) {
  64. $clientData = $this->clientStorage->getClientDetails($this->client_id);
  65. $registered_redirect_uri = $clientData['redirect_uri'];
  66. }
  67. // the user declined access to the client's application
  68. if ($is_authorized === false) {
  69. $redirect_uri = $this->redirect_uri ?: $registered_redirect_uri;
  70. $this->setNotAuthorizedResponse($request, $response, $redirect_uri, $user_id);
  71. return;
  72. }
  73. // build the parameters to set in the redirect URI
  74. if (!$params = $this->buildAuthorizeParameters($request, $response, $user_id)) {
  75. return;
  76. }
  77. $authResult = $this->responseTypes[$this->response_type]->getAuthorizeResponse($params, $user_id);
  78. list($redirect_uri, $uri_params) = $authResult;
  79. if (empty($redirect_uri) && !empty($registered_redirect_uri)) {
  80. $redirect_uri = $registered_redirect_uri;
  81. }
  82. $uri = $this->buildUri($redirect_uri, $uri_params);
  83. // return redirect response
  84. $response->setRedirect($this->config['redirect_status_code'], $uri);
  85. }
  86. protected function setNotAuthorizedResponse(RequestInterface $request, ResponseInterface $response, $redirect_uri, $user_id = null)
  87. {
  88. $error = 'access_denied';
  89. $error_message = 'The user denied access to your application';
  90. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $this->state, $error, $error_message);
  91. }
  92. /*
  93. * We have made this protected so this class can be extended to add/modify
  94. * these parameters
  95. */
  96. protected function buildAuthorizeParameters($request, $response, $user_id)
  97. {
  98. // @TODO: we should be explicit with this in the future
  99. $params = array(
  100. 'scope' => $this->scope,
  101. 'state' => $this->state,
  102. 'client_id' => $this->client_id,
  103. 'redirect_uri' => $this->redirect_uri,
  104. 'response_type' => $this->response_type,
  105. );
  106. return $params;
  107. }
  108. public function validateAuthorizeRequest(RequestInterface $request, ResponseInterface $response)
  109. {
  110. // Make sure a valid client id was supplied (we can not redirect because we were unable to verify the URI)
  111. if (!$client_id = $request->query('client_id', $request->request('client_id'))) {
  112. // We don't have a good URI to use
  113. $response->setError(400, 'invalid_client', "No client id supplied");
  114. return false;
  115. }
  116. // Get client details
  117. if (!$clientData = $this->clientStorage->getClientDetails($client_id)) {
  118. $response->setError(400, 'invalid_client', 'The client id supplied is invalid');
  119. return false;
  120. }
  121. $registered_redirect_uri = isset($clientData['redirect_uri']) ? $clientData['redirect_uri'] : '';
  122. // Make sure a valid redirect_uri was supplied. If specified, it must match the clientData URI.
  123. // @see http://tools.ietf.org/html/rfc6749#section-3.1.2
  124. // @see http://tools.ietf.org/html/rfc6749#section-4.1.2.1
  125. // @see http://tools.ietf.org/html/rfc6749#section-4.2.2.1
  126. if ($supplied_redirect_uri = $request->query('redirect_uri', $request->request('redirect_uri'))) {
  127. // validate there is no fragment supplied
  128. $parts = parse_url($supplied_redirect_uri);
  129. if (isset($parts['fragment']) && $parts['fragment']) {
  130. $response->setError(400, 'invalid_uri', 'The redirect URI must not contain a fragment');
  131. return false;
  132. }
  133. // validate against the registered redirect uri(s) if available
  134. if ($registered_redirect_uri && !$this->validateRedirectUri($supplied_redirect_uri, $registered_redirect_uri)) {
  135. $response->setError(400, 'redirect_uri_mismatch', 'The redirect URI provided is missing or does not match', '#section-3.1.2');
  136. return false;
  137. }
  138. $redirect_uri = $supplied_redirect_uri;
  139. } else {
  140. // use the registered redirect_uri if none has been supplied, if possible
  141. if (!$registered_redirect_uri) {
  142. $response->setError(400, 'invalid_uri', 'No redirect URI was supplied or stored');
  143. return false;
  144. }
  145. if (count(explode(' ', $registered_redirect_uri)) > 1) {
  146. $response->setError(400, 'invalid_uri', 'A redirect URI must be supplied when multiple redirect URIs are registered', '#section-3.1.2.3');
  147. return false;
  148. }
  149. $redirect_uri = $registered_redirect_uri;
  150. }
  151. // Select the redirect URI
  152. $response_type = $request->query('response_type', $request->request('response_type'));
  153. // for multiple-valued response types - make them alphabetical
  154. if (false !== strpos($response_type, ' ')) {
  155. $types = explode(' ', $response_type);
  156. sort($types);
  157. $response_type = ltrim(implode(' ', $types));
  158. }
  159. $state = $request->query('state', $request->request('state'));
  160. // type and client_id are required
  161. if (!$response_type || !in_array($response_type, $this->getValidResponseTypes())) {
  162. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'invalid_request', 'Invalid or missing response type', null);
  163. return false;
  164. }
  165. if ($response_type == self::RESPONSE_TYPE_AUTHORIZATION_CODE) {
  166. if (!isset($this->responseTypes['code'])) {
  167. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'unsupported_response_type', 'authorization code grant type not supported', null);
  168. return false;
  169. }
  170. if (!$this->clientStorage->checkRestrictedGrantType($client_id, 'authorization_code')) {
  171. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'unauthorized_client', 'The grant type is unauthorized for this client_id', null);
  172. return false;
  173. }
  174. if ($this->responseTypes['code']->enforceRedirect() && !$redirect_uri) {
  175. $response->setError(400, 'redirect_uri_mismatch', 'The redirect URI is mandatory and was not supplied');
  176. return false;
  177. }
  178. } else {
  179. if (!$this->config['allow_implicit']) {
  180. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'unsupported_response_type', 'implicit grant type not supported', null);
  181. return false;
  182. }
  183. if (!$this->clientStorage->checkRestrictedGrantType($client_id, 'implicit')) {
  184. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'unauthorized_client', 'The grant type is unauthorized for this client_id', null);
  185. return false;
  186. }
  187. }
  188. // validate requested scope if it exists
  189. $requestedScope = $this->scopeUtil->getScopeFromRequest($request);
  190. if ($requestedScope) {
  191. // restrict scope by client specific scope if applicable,
  192. // otherwise verify the scope exists
  193. $clientScope = $this->clientStorage->getClientScope($client_id);
  194. if ((is_null($clientScope) && !$this->scopeUtil->scopeExists($requestedScope))
  195. || ($clientScope && !$this->scopeUtil->checkScope($requestedScope, $clientScope))) {
  196. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'invalid_scope', 'An unsupported scope was requested', null);
  197. return false;
  198. }
  199. } else {
  200. // use a globally-defined default scope
  201. $defaultScope = $this->scopeUtil->getDefaultScope($client_id);
  202. if (false === $defaultScope) {
  203. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'invalid_client', 'This application requires you specify a scope parameter', null);
  204. return false;
  205. }
  206. $requestedScope = $defaultScope;
  207. }
  208. // Validate state parameter exists (if configured to enforce this)
  209. if ($this->config['enforce_state'] && !$state) {
  210. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, null, 'invalid_request', 'The state parameter is required');
  211. return false;
  212. }
  213. // save the input data and return true
  214. $this->scope = $requestedScope;
  215. $this->state = $state;
  216. $this->client_id = $client_id;
  217. // Only save the SUPPLIED redirect URI (@see http://tools.ietf.org/html/rfc6749#section-4.1.3)
  218. $this->redirect_uri = $supplied_redirect_uri;
  219. $this->response_type = $response_type;
  220. return true;
  221. }
  222. /**
  223. * Build the absolute URI based on supplied URI and parameters.
  224. *
  225. * @param $uri An absolute URI.
  226. * @param $params Parameters to be append as GET.
  227. *
  228. * @return
  229. * An absolute URI with supplied parameters.
  230. *
  231. * @ingroup oauth2_section_4
  232. */
  233. private function buildUri($uri, $params)
  234. {
  235. $parse_url = parse_url($uri);
  236. // Add our params to the parsed uri
  237. foreach ($params as $k => $v) {
  238. if (isset($parse_url[$k])) {
  239. $parse_url[$k] .= "&" . http_build_query($v, '', '&');
  240. } else {
  241. $parse_url[$k] = http_build_query($v, '', '&');
  242. }
  243. }
  244. // Put humpty dumpty back together
  245. return
  246. ((isset($parse_url["scheme"])) ? $parse_url["scheme"] . "://" : "")
  247. . ((isset($parse_url["user"])) ? $parse_url["user"]
  248. . ((isset($parse_url["pass"])) ? ":" . $parse_url["pass"] : "") . "@" : "")
  249. . ((isset($parse_url["host"])) ? $parse_url["host"] : "")
  250. . ((isset($parse_url["port"])) ? ":" . $parse_url["port"] : "")
  251. . ((isset($parse_url["path"])) ? $parse_url["path"] : "")
  252. . ((isset($parse_url["query"]) && !empty($parse_url['query'])) ? "?" . $parse_url["query"] : "")
  253. . ((isset($parse_url["fragment"])) ? "#" . $parse_url["fragment"] : "")
  254. ;
  255. }
  256. protected function getValidResponseTypes()
  257. {
  258. return array(
  259. self::RESPONSE_TYPE_ACCESS_TOKEN,
  260. self::RESPONSE_TYPE_AUTHORIZATION_CODE,
  261. );
  262. }
  263. /**
  264. * Internal method for validating redirect URI supplied
  265. *
  266. * @param string $inputUri The submitted URI to be validated
  267. * @param string $registeredUriString The allowed URI(s) to validate against. Can be a space-delimited string of URIs to
  268. * allow for multiple URIs
  269. *
  270. * @see http://tools.ietf.org/html/rfc6749#section-3.1.2
  271. */
  272. protected function validateRedirectUri($inputUri, $registeredUriString)
  273. {
  274. if (!$inputUri || !$registeredUriString) {
  275. return false; // if either one is missing, assume INVALID
  276. }
  277. $registered_uris = preg_split('/\s+/', $registeredUriString);
  278. foreach ($registered_uris as $registered_uri) {
  279. if ($this->config['require_exact_redirect_uri']) {
  280. // the input uri is validated against the registered uri using exact match
  281. if (strcmp($inputUri, $registered_uri) === 0) {
  282. return true;
  283. }
  284. } else {
  285. // the input uri is validated against the registered uri using case-insensitive match of the initial string
  286. // i.e. additional query parameters may be applied
  287. if (strcasecmp(substr($inputUri, 0, strlen($registered_uri)), $registered_uri) === 0) {
  288. return true;
  289. }
  290. }
  291. }
  292. return false;
  293. }
  294. /**
  295. * Convenience methods to access the parameters derived from the validated request
  296. */
  297. public function getScope()
  298. {
  299. return $this->scope;
  300. }
  301. public function getState()
  302. {
  303. return $this->state;
  304. }
  305. public function getClientId()
  306. {
  307. return $this->client_id;
  308. }
  309. public function getRedirectUri()
  310. {
  311. return $this->redirect_uri;
  312. }
  313. public function getResponseType()
  314. {
  315. return $this->response_type;
  316. }
  317. }