AuthorizeController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. /**
  109. * @param RequestInterface $request
  110. * @param ResponseInterface $response
  111. * @return bool
  112. */
  113. public function validateAuthorizeRequest(RequestInterface $request, ResponseInterface $response)
  114. {
  115. // Make sure a valid client id was supplied (we can not redirect because we were unable to verify the URI)
  116. if (!$client_id = $request->query('client_id', $request->request('client_id'))) {
  117. // We don't have a good URI to use
  118. $response->setError(400, 'invalid_client', "No client id supplied");
  119. return false;
  120. }
  121. // Get client details
  122. if (!$clientData = $this->clientStorage->getClientDetails($client_id)) {
  123. $response->setError(400, 'invalid_client', 'The client id supplied is invalid');
  124. return false;
  125. }
  126. $registered_redirect_uri = isset($clientData['redirect_uri']) ? $clientData['redirect_uri'] : '';
  127. // Make sure a valid redirect_uri was supplied. If specified, it must match the clientData URI.
  128. // @see http://tools.ietf.org/html/rfc6749#section-3.1.2
  129. // @see http://tools.ietf.org/html/rfc6749#section-4.1.2.1
  130. // @see http://tools.ietf.org/html/rfc6749#section-4.2.2.1
  131. if ($supplied_redirect_uri = $request->query('redirect_uri', $request->request('redirect_uri'))) {
  132. // validate there is no fragment supplied
  133. $parts = parse_url($supplied_redirect_uri);
  134. if (isset($parts['fragment']) && $parts['fragment']) {
  135. $response->setError(400, 'invalid_uri', 'The redirect URI must not contain a fragment');
  136. return false;
  137. }
  138. // validate against the registered redirect uri(s) if available
  139. if ($registered_redirect_uri && !$this->validateRedirectUri($supplied_redirect_uri, $registered_redirect_uri)) {
  140. $response->setError(400, 'redirect_uri_mismatch', 'The redirect URI provided is missing or does not match', '#section-3.1.2');
  141. return false;
  142. }
  143. $redirect_uri = $supplied_redirect_uri;
  144. } else {
  145. // use the registered redirect_uri if none has been supplied, if possible
  146. if (!$registered_redirect_uri) {
  147. $response->setError(400, 'invalid_uri', 'No redirect URI was supplied or stored');
  148. return false;
  149. }
  150. if (count(explode(' ', $registered_redirect_uri)) > 1) {
  151. $response->setError(400, 'invalid_uri', 'A redirect URI must be supplied when multiple redirect URIs are registered', '#section-3.1.2.3');
  152. return false;
  153. }
  154. $redirect_uri = $registered_redirect_uri;
  155. }
  156. // Select the redirect URI
  157. $response_type = $request->query('response_type', $request->request('response_type'));
  158. // for multiple-valued response types - make them alphabetical
  159. if (false !== strpos($response_type, ' ')) {
  160. $types = explode(' ', $response_type);
  161. sort($types);
  162. $response_type = ltrim(implode(' ', $types));
  163. }
  164. $state = $request->query('state', $request->request('state'));
  165. // type and client_id are required
  166. if (!$response_type || !in_array($response_type, $this->getValidResponseTypes())) {
  167. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'invalid_request', 'Invalid or missing response type', null);
  168. return false;
  169. }
  170. if ($response_type == self::RESPONSE_TYPE_AUTHORIZATION_CODE) {
  171. if (!isset($this->responseTypes['code'])) {
  172. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'unsupported_response_type', 'authorization code grant type not supported', null);
  173. return false;
  174. }
  175. if (!$this->clientStorage->checkRestrictedGrantType($client_id, 'authorization_code')) {
  176. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'unauthorized_client', 'The grant type is unauthorized for this client_id', null);
  177. return false;
  178. }
  179. if ($this->responseTypes['code']->enforceRedirect() && !$redirect_uri) {
  180. $response->setError(400, 'redirect_uri_mismatch', 'The redirect URI is mandatory and was not supplied');
  181. return false;
  182. }
  183. } else {
  184. if (!$this->config['allow_implicit']) {
  185. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'unsupported_response_type', 'implicit grant type not supported', null);
  186. return false;
  187. }
  188. if (!$this->clientStorage->checkRestrictedGrantType($client_id, 'implicit')) {
  189. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'unauthorized_client', 'The grant type is unauthorized for this client_id', null);
  190. return false;
  191. }
  192. }
  193. // validate requested scope if it exists
  194. $requestedScope = $this->scopeUtil->getScopeFromRequest($request);
  195. if ($requestedScope) {
  196. // restrict scope by client specific scope if applicable,
  197. // otherwise verify the scope exists
  198. $clientScope = $this->clientStorage->getClientScope($client_id);
  199. if ((empty($clientScope) && !$this->scopeUtil->scopeExists($requestedScope))
  200. || (!empty($clientScope) && !$this->scopeUtil->checkScope($requestedScope, $clientScope))) {
  201. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'invalid_scope', 'An unsupported scope was requested', null);
  202. return false;
  203. }
  204. } else {
  205. // use a globally-defined default scope
  206. $defaultScope = $this->scopeUtil->getDefaultScope($client_id);
  207. if (false === $defaultScope) {
  208. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'invalid_client', 'This application requires you specify a scope parameter', null);
  209. return false;
  210. }
  211. $requestedScope = $defaultScope;
  212. }
  213. // Validate state parameter exists (if configured to enforce this)
  214. if ($this->config['enforce_state'] && !$state) {
  215. $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, null, 'invalid_request', 'The state parameter is required');
  216. return false;
  217. }
  218. // save the input data and return true
  219. $this->scope = $requestedScope;
  220. $this->state = $state;
  221. $this->client_id = $client_id;
  222. // Only save the SUPPLIED redirect URI (@see http://tools.ietf.org/html/rfc6749#section-4.1.3)
  223. $this->redirect_uri = $supplied_redirect_uri;
  224. $this->response_type = $response_type;
  225. return true;
  226. }
  227. /**
  228. * Build the absolute URI based on supplied URI and parameters.
  229. *
  230. * @param $uri An absolute URI.
  231. * @param $params Parameters to be append as GET.
  232. *
  233. * @return
  234. * An absolute URI with supplied parameters.
  235. *
  236. * @ingroup oauth2_section_4
  237. */
  238. private function buildUri($uri, $params)
  239. {
  240. $parse_url = parse_url($uri);
  241. // Add our params to the parsed uri
  242. foreach ($params as $k => $v) {
  243. if (isset($parse_url[$k])) {
  244. $parse_url[$k] .= "&" . http_build_query($v, '', '&');
  245. } else {
  246. $parse_url[$k] = http_build_query($v, '', '&');
  247. }
  248. }
  249. // Put humpty dumpty back together
  250. return
  251. ((isset($parse_url["scheme"])) ? $parse_url["scheme"] . "://" : "")
  252. . ((isset($parse_url["user"])) ? $parse_url["user"]
  253. . ((isset($parse_url["pass"])) ? ":" . $parse_url["pass"] : "") . "@" : "")
  254. . ((isset($parse_url["host"])) ? $parse_url["host"] : "")
  255. . ((isset($parse_url["port"])) ? ":" . $parse_url["port"] : "")
  256. . ((isset($parse_url["path"])) ? $parse_url["path"] : "")
  257. . ((isset($parse_url["query"]) && !empty($parse_url['query'])) ? "?" . $parse_url["query"] : "")
  258. . ((isset($parse_url["fragment"])) ? "#" . $parse_url["fragment"] : "")
  259. ;
  260. }
  261. protected function getValidResponseTypes()
  262. {
  263. return array(
  264. self::RESPONSE_TYPE_ACCESS_TOKEN,
  265. self::RESPONSE_TYPE_AUTHORIZATION_CODE,
  266. );
  267. }
  268. /**
  269. * Internal method for validating redirect URI supplied
  270. *
  271. * @param string $inputUri The submitted URI to be validated
  272. * @param string $registeredUriString The allowed URI(s) to validate against. Can be a space-delimited string of URIs to
  273. * allow for multiple URIs
  274. *
  275. * @see http://tools.ietf.org/html/rfc6749#section-3.1.2
  276. */
  277. protected function validateRedirectUri($inputUri, $registeredUriString)
  278. {
  279. if (!$inputUri || !$registeredUriString) {
  280. return false; // if either one is missing, assume INVALID
  281. }
  282. $registered_uris = preg_split('/\s+/', $registeredUriString);
  283. foreach ($registered_uris as $registered_uri) {
  284. if ($this->config['require_exact_redirect_uri']) {
  285. // the input uri is validated against the registered uri using exact match
  286. if (strcmp($inputUri, $registered_uri) === 0) {
  287. return true;
  288. }
  289. } else {
  290. $registered_uri_length = strlen($registered_uri);
  291. if ($registered_uri_length === 0) {
  292. return false;
  293. }
  294. // the input uri is validated against the registered uri using case-insensitive match of the initial string
  295. // i.e. additional query parameters may be applied
  296. if (strcasecmp(substr($inputUri, 0, $registered_uri_length), $registered_uri) === 0) {
  297. return true;
  298. }
  299. }
  300. }
  301. return false;
  302. }
  303. /**
  304. * Convenience methods to access the parameters derived from the validated request
  305. */
  306. public function getScope()
  307. {
  308. return $this->scope;
  309. }
  310. public function getState()
  311. {
  312. return $this->state;
  313. }
  314. public function getClientId()
  315. {
  316. return $this->client_id;
  317. }
  318. public function getRedirectUri()
  319. {
  320. return $this->redirect_uri;
  321. }
  322. public function getResponseType()
  323. {
  324. return $this->response_type;
  325. }
  326. }