oauth2-server/examples/public/secured_route.php

73 lines
2.1 KiB
PHP
Raw Normal View History

2016-01-17 14:56:51 +00:00
<?php
2016-02-12 19:06:31 +01:00
use League\OAuth2\Server\Exception\OAuthServerException;
2016-01-17 14:56:51 +00:00
use League\OAuth2\Server\Server;
use OAuth2ServerExamples\Repositories\AccessTokenRepository;
use OAuth2ServerExamples\Repositories\ClientRepository;
use OAuth2ServerExamples\Repositories\ScopeRepository;
2016-02-12 19:06:31 +01:00
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
2016-01-17 14:56:51 +00:00
use Slim\App;
2016-02-12 19:06:31 +01:00
use Zend\Diactoros\Stream;
2016-01-17 14:56:51 +00:00
include(__DIR__ . '/../vendor/autoload.php');
$app = new App([
'settings' => [
'displayErrorDetails' => true,
],
Server::class => function () {
// Init our repositories
$clientRepository = new ClientRepository();
$accessTokenRepository = new AccessTokenRepository();
2016-02-12 19:06:31 +01:00
$scopeRepository = new ScopeRepository();
2016-01-17 14:56:51 +00:00
$privateKeyPath = 'file://' . __DIR__ . '/../private.key';
$publicKeyPath = 'file://' . __DIR__ . '/../public.key';
// Setup the authorization server
2016-02-12 19:06:31 +01:00
return new Server(
2016-01-17 14:56:51 +00:00
$clientRepository,
$accessTokenRepository,
$scopeRepository,
$privateKeyPath,
$publicKeyPath
);
}
]);
2016-02-12 19:06:31 +01:00
$app->get('/user', function (ServerRequestInterface $request, ResponseInterface $response) use ($app) {
$server = $app->getContainer()->get(Server::class);
$body = new Stream('php://temp', 'r+');
try {
$request = $server->validateRequest($request);
} catch (OAuthServerException $exception) {
return $exception->generateHttpResponse($response);
} catch (\Exception $exception) {
$body->write($exception->getMessage());
return $response->withStatus(500)->withBody($body);
}
2016-01-17 14:56:51 +00:00
$params = [];
if (in_array('basic', $request->getAttribute('oauth_scopes', []))) {
$params = [
'id' => 1,
'name' => 'Alex',
'city' => 'London'
];
}
if (in_array('email', $request->getAttribute('oauth_scopes', []))) {
$params['email'] = 'alex@example.com';
}
2016-02-12 19:06:31 +01:00
$body->write(json_encode($params));
2016-01-17 14:56:51 +00:00
2016-02-12 19:06:31 +01:00
return $response->withBody($body);
2016-01-17 14:56:51 +00:00
});
$app->run();