This repository has been archived by the owner on Jan 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 92
/
AuthController.php
370 lines (323 loc) · 11.1 KB
/
AuthController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
<?php
/**
* @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
* @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com)
*/
namespace ZF\OAuth2\Controller;
use InvalidArgumentException;
use OAuth2\Request as OAuth2Request;
use OAuth2\Response as OAuth2Response;
use OAuth2\Server as OAuth2Server;
use RuntimeException;
use Zend\Http\PhpEnvironment\Request as PhpEnvironmentRequest;
use Zend\Http\Request as HttpRequest;
use Zend\Mvc\Controller\AbstractActionController;
use ZF\ApiProblem\ApiProblem;
use ZF\ApiProblem\ApiProblemResponse;
use ZF\ApiProblem\Exception\ProblemExceptionInterface;
use ZF\ContentNegotiation\ViewModel;
use ZF\OAuth2\Provider\UserId\UserIdProviderInterface;
class AuthController extends AbstractActionController
{
/**
* @var boolean
*/
protected $apiProblemErrorResponse = true;
/**
* @var OAuth2Server
*/
protected $server;
/**
* @var callable Factory for generating an OAuth2Server instance.
*/
protected $serverFactory;
/**
* @var UserIdProviderInterface
*/
protected $userIdProvider;
/**
* Constructor
*
* @param callable $serverFactory
* @param UserIdProviderInterface $userIdProvider
*/
public function __construct($serverFactory, UserIdProviderInterface $userIdProvider)
{
if (! is_callable($serverFactory)) {
throw new InvalidArgumentException(sprintf(
'OAuth2 Server factory must be a PHP callable; received %s',
(is_object($serverFactory) ? get_class($serverFactory) : gettype($serverFactory))
));
}
$this->serverFactory = $serverFactory;
$this->userIdProvider = $userIdProvider;
}
/**
* Should the controller return ApiProblemResponse?
*
* @return bool
*/
public function isApiProblemErrorResponse()
{
return $this->apiProblemErrorResponse;
}
/**
* Indicate whether ApiProblemResponse or oauth2 errors should be returned.
*
* Boolean true indicates ApiProblemResponse should be returned (the
* default), while false indicates oauth2 errors (per the oauth2 spec)
* should be returned.
*
* @param bool $apiProblemErrorResponse
*/
public function setApiProblemErrorResponse($apiProblemErrorResponse)
{
$this->apiProblemErrorResponse = (bool) $apiProblemErrorResponse;
}
/**
* Token Action (/oauth)
*/
public function tokenAction()
{
$request = $this->getRequest();
if (! $request instanceof HttpRequest) {
// not an HTTP request; nothing left to do
return;
}
if ($request->isOptions()) {
// OPTIONS request.
// This is most likely a CORS attempt; as such, pass the response on.
return $this->getResponse();
}
$oauth2request = $this->getOAuth2Request();
$oauth2server = $this->getOAuth2Server($this->params('oauth'));
try {
$response = $oauth2server->handleTokenRequest($oauth2request);
} catch (ProblemExceptionInterface $ex) {
$status = $ex->getCode() ?: 401;
$status = $status >= 400 && $status < 600 ? $status : 401;
return new ApiProblemResponse(
new ApiProblem($status, $ex)
);
}
if ($response->isClientError()) {
return $this->getErrorResponse($response);
}
return $this->setHttpResponse($response);
}
/**
* Token Revoke (/oauth/revoke)
*/
public function revokeAction()
{
$request = $this->getRequest();
if (! $request instanceof HttpRequest) {
// not an HTTP request; nothing left to do
return;
}
if ($request->isOptions()) {
// OPTIONS request.
// This is most likely a CORS attempt; as such, pass the response on.
return $this->getResponse();
}
$oauth2request = $this->getOAuth2Request();
$response = $this->getOAuth2Server($this->params('oauth'))->handleRevokeRequest($oauth2request);
if ($response->isClientError()) {
return $this->getErrorResponse($response);
}
return $this->setHttpResponse($response);
}
/**
* Test resource (/oauth/resource)
*/
public function resourceAction()
{
$server = $this->getOAuth2Server($this->params('oauth'));
// Handle a request for an OAuth2.0 Access Token and send the response to the client
if (! $server->verifyResourceRequest($this->getOAuth2Request())) {
$response = $server->getResponse();
return $this->getApiProblemResponse($response);
}
$httpResponse = $this->getResponse();
$httpResponse->setStatusCode(200);
$httpResponse->getHeaders()->addHeaders(['Content-type' => 'application/json']);
$httpResponse->setContent(
json_encode(['success' => true, 'message' => 'You accessed my APIs!'])
);
return $httpResponse;
}
/**
* Authorize action (/oauth/authorize)
*/
public function authorizeAction()
{
$server = $this->getOAuth2Server($this->params('oauth'));
$request = $this->getOAuth2Request();
$response = new OAuth2Response();
// validate the authorize request
$isValid = $this->server->validateAuthorizeRequest($request, $response);
if (! $isValid) {
return $this->getErrorResponse($response);
}
$authorized = $request->request('authorized', false);
if (empty($authorized)) {
$clientId = $request->query('client_id', false);
$view = new ViewModel(['clientId' => $clientId]);
$view->setTemplate('oauth/authorize');
return $view;
}
$isAuthorized = ($authorized === 'yes');
$userIdProvider = $this->userIdProvider;
$this->server->handleAuthorizeRequest(
$request,
$response,
$isAuthorized,
$userIdProvider($this->getRequest())
);
$redirect = $response->getHttpHeader('Location');
if (! empty($redirect)) {
return $this->redirect()->toUrl($redirect);
}
return $this->getErrorResponse($response);
}
/**
* Receive code action prints the code/token access
*/
public function receiveCodeAction()
{
$code = $this->params()->fromQuery('code', false);
$view = new ViewModel([
'code' => $code
]);
$view->setTemplate('oauth/receive-code');
return $view;
}
/**
* @param OAuth2Response $response
* @return ApiProblemResponse|\Zend\Stdlib\ResponseInterface
*/
protected function getErrorResponse(OAuth2Response $response)
{
if ($this->isApiProblemErrorResponse()) {
return $this->getApiProblemResponse($response);
}
return $this->setHttpResponse($response);
}
/**
* Map OAuth2Response to ApiProblemResponse
*
* @param OAuth2Response $response
* @return ApiProblemResponse
*/
protected function getApiProblemResponse(OAuth2Response $response)
{
$parameters = $response->getParameters();
$errorUri = isset($parameters['error_uri']) ? $parameters['error_uri'] : null;
$error = isset($parameters['error']) ? $parameters['error'] : null;
$errorDescription = isset($parameters['error_description']) ? $parameters['error_description'] : null;
return new ApiProblemResponse(
new ApiProblem(
$response->getStatusCode(),
$errorDescription,
$errorUri,
$error
)
);
}
/**
* Create an OAuth2 request based on the ZF2 request object
*
* Marshals:
*
* - query string
* - body parameters, via content negotiation
* - "server", specifically the request method and content type
* - raw content
* - headers
*
* This ensures that JSON requests providing credentials for OAuth2
* verification/validation can be processed.
*
* @return OAuth2Request
*/
protected function getOAuth2Request()
{
$zf2Request = $this->getRequest();
$headers = $zf2Request->getHeaders();
// Marshal content type, so we can seed it into the $_SERVER array
$contentType = '';
if ($headers->has('Content-Type')) {
$contentType = $headers->get('Content-Type')->getFieldValue();
}
// Get $_SERVER superglobal
$server = [];
if ($zf2Request instanceof PhpEnvironmentRequest) {
$server = $zf2Request->getServer()->toArray();
} elseif (! empty($_SERVER)) {
$server = $_SERVER;
}
$server['REQUEST_METHOD'] = $zf2Request->getMethod();
// Seed headers with HTTP auth information
$headers = $headers->toArray();
if (isset($server['PHP_AUTH_USER'])) {
$headers['PHP_AUTH_USER'] = $server['PHP_AUTH_USER'];
}
if (isset($server['PHP_AUTH_PW'])) {
$headers['PHP_AUTH_PW'] = $server['PHP_AUTH_PW'];
}
// Ensure the bodyParams are passed as an array
$bodyParams = $this->bodyParams() ?: [];
return new OAuth2Request(
$zf2Request->getQuery()->toArray(),
$bodyParams,
[], // attributes
[], // cookies
[], // files
$server,
$zf2Request->getContent(),
$headers
);
}
/**
* Convert the OAuth2 response to a \Zend\Http\Response
*
* @param $response OAuth2Response
* @return \Zend\Http\Response
*/
private function setHttpResponse(OAuth2Response $response)
{
$httpResponse = $this->getResponse();
$httpResponse->setStatusCode($response->getStatusCode());
$headers = $httpResponse->getHeaders();
$headers->addHeaders($response->getHttpHeaders());
$headers->addHeaderLine('Content-type', 'application/json');
$httpResponse->setContent($response->getResponseBody());
return $httpResponse;
}
/**
* Retrieve the OAuth2\Server instance.
*
* If not already created by the composed $serverFactory, that callable
* is invoked with the provided $type as an argument, and the value
* returned.
*
* @param string $type
* @return OAuth2Server
* @throws RuntimeException if the factory does not return an OAuth2Server instance.
*/
private function getOAuth2Server($type)
{
if ($this->server instanceof OAuth2Server) {
return $this->server;
}
$server = call_user_func($this->serverFactory, $type);
if (! $server instanceof OAuth2Server) {
throw new RuntimeException(sprintf(
'OAuth2\Server factory did not return a valid instance; received %s',
(is_object($server) ? get_class($server) : gettype($server))
));
}
$this->server = $server;
return $server;
}
}