73 lines
2.2 KiB
PHP
Raw Normal View History

2016-03-24 15:27:55 +00:00
<?php
2016-04-17 12:41:28 +01:00
use League\OAuth2\Server\ResourceServer;
2016-03-24 15:27:55 +00:00
use OAuth2ServerExamples\Repositories\AccessTokenRepository;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\App;
include __DIR__ . '/../vendor/autoload.php';
$app = new App([
2016-04-18 12:23:21 +01:00
// Add the resource server to the DI container
2016-04-17 12:54:49 +01:00
ResourceServer::class => function () {
2016-04-17 12:41:28 +01:00
$server = new ResourceServer(
2016-04-18 12:23:21 +01:00
new AccessTokenRepository(), // instance of AccessTokenRepositoryInterface
'file://' . __DIR__ . '/../public.key' // the authorization server's public key
2016-03-24 15:27:55 +00:00
);
return $server;
},
]);
2016-04-18 12:23:21 +01:00
// Add the resource server middleware which will intercept and validate requests
2016-03-24 15:27:55 +00:00
$app->add(
new \League\OAuth2\Server\Middleware\ResourceServerMiddleware(
2016-04-17 12:54:49 +01:00
$app->getContainer()->get(ResourceServer::class)
2016-03-24 15:27:55 +00:00
)
);
2016-04-18 12:23:21 +01:00
// An example endpoint secured with OAuth 2.0
$app->get(
'/users',
function (ServerRequestInterface $request, ResponseInterface $response) use ($app) {
$users = [
[
'id' => 123,
'name' => 'Alex',
'email' => 'alex@thephpleague.com',
],
[
'id' => 124,
'name' => 'Frank',
'email' => 'frank@thephpleague.com',
],
[
'id' => 125,
'name' => 'Phil',
'email' => 'phil@thephpleague.com',
],
];
2016-03-24 15:27:55 +00:00
2016-04-18 12:23:21 +01:00
// If the access token doesn't have the `basic` scope hide users' names
if (in_array('basic', $request->getAttribute('oauth_scopes')) === false) {
for ($i = 0; $i < count($users); $i++) {
unset($users[$i]['name']);
}
2016-03-24 15:27:55 +00:00
}
2016-04-18 12:23:21 +01:00
// If the access token doesn't have the `email` scope hide users' email addresses
if (in_array('email', $request->getAttribute('oauth_scopes')) === false) {
for ($i = 0; $i < count($users); $i++) {
unset($users[$i]['email']);
}
2016-03-24 15:27:55 +00:00
}
2016-04-18 12:23:21 +01:00
$response->getBody()->write(json_encode($users));
2016-03-24 15:27:55 +00:00
2016-04-18 12:23:21 +01:00
return $response->withStatus(200);
}
);
2016-03-24 15:27:55 +00:00
2016-09-13 14:17:09 +00:00
$app->run();