Improved examples

This commit is contained in:
Alex Bilbie 2016-04-18 12:23:21 +01:00
parent f80d0d39a4
commit e885114714
2 changed files with 79 additions and 85 deletions

View File

@ -1,11 +1,4 @@
<?php <?php
/**
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
use League\OAuth2\Server\ResourceServer; use League\OAuth2\Server\ResourceServer;
use OAuth2ServerExamples\Repositories\AccessTokenRepository; use OAuth2ServerExamples\Repositories\AccessTokenRepository;
@ -16,63 +9,65 @@ use Slim\App;
include __DIR__ . '/../vendor/autoload.php'; include __DIR__ . '/../vendor/autoload.php';
$app = new App([ $app = new App([
'settings' => [ // Add the resource server to the DI container
'displayErrorDetails' => true,
],
ResourceServer::class => function () { ResourceServer::class => function () {
// Setup the authorization server
$server = new ResourceServer( $server = new ResourceServer(
new AccessTokenRepository(), new AccessTokenRepository(), // instance of AccessTokenRepositoryInterface
'file://' . __DIR__ . '/../public.key' 'file://' . __DIR__ . '/../public.key' // the authorization server's public key
); );
return $server; return $server;
}, },
]); ]);
// Add the resource server middleware which will intercept and validate requests
$app->add( $app->add(
new \League\OAuth2\Server\Middleware\ResourceServerMiddleware( new \League\OAuth2\Server\Middleware\ResourceServerMiddleware(
$app->getContainer()->get(ResourceServer::class) $app->getContainer()->get(ResourceServer::class)
) )
); );
$app->get('/users', function (ServerRequestInterface $request, ResponseInterface $response) use ($app) { // An example endpoint secured with OAuth 2.0
$app->get(
'/users',
function (ServerRequestInterface $request, ResponseInterface $response) use ($app) {
$users = [ $users = [
[ [
'id' => 123, 'id' => 123,
'name' => 'Alex', 'name' => 'Alex',
'email' => 'alex@thephpleague.com', 'email' => 'alex@thephpleague.com',
], ],
[ [
'id' => 124, 'id' => 124,
'name' => 'Frank', 'name' => 'Frank',
'email' => 'frank@thephpleague.com', 'email' => 'frank@thephpleague.com',
], ],
[ [
'id' => 125, 'id' => 125,
'name' => 'Phil', 'name' => 'Phil',
'email' => 'phil@thephpleague.com', 'email' => 'phil@thephpleague.com',
], ],
]; ];
// If the access token doesn't have the `basic` scope hide users' names // If the access token doesn't have the `basic` scope hide users' names
if (in_array('basic', $request->getAttribute('oauth_scopes')) === false) { if (in_array('basic', $request->getAttribute('oauth_scopes')) === false) {
for ($i = 0; $i < count($users); $i++) { for ($i = 0; $i < count($users); $i++) {
unset($users[$i]['name']); unset($users[$i]['name']);
}
} }
}
// If the access token doesn't have the `emal` scope hide users' email addresses // If the access token doesn't have the `email` scope hide users' email addresses
if (in_array('email', $request->getAttribute('oauth_scopes')) === false) { if (in_array('email', $request->getAttribute('oauth_scopes')) === false) {
for ($i = 0; $i < count($users); $i++) { for ($i = 0; $i < count($users); $i++) {
unset($users[$i]['email']); unset($users[$i]['email']);
}
} }
$response->getBody()->write(json_encode($users));
return $response->withStatus(200);
} }
);
$response->getBody()->write(json_encode($users));
return $response->withStatus(200);
});
$app->run(); $app->run();

View File

@ -1,11 +1,4 @@
<?php <?php
/**
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
use League\OAuth2\Server\AuthorizationServer; use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Exception\OAuthServerException; use League\OAuth2\Server\Exception\OAuthServerException;
@ -18,58 +11,64 @@ use OAuth2ServerExamples\Repositories\UserRepository;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use Slim\App; use Slim\App;
use Zend\Diactoros\Stream;
include __DIR__ . '/../vendor/autoload.php'; include __DIR__ . '/../vendor/autoload.php';
$app = new App([ $app = new App([
'settings' => [ // Add the authorization server to the DI container
'displayErrorDetails' => true,
],
AuthorizationServer::class => function () { AuthorizationServer::class => function () {
// Init our repositories
$clientRepository = new ClientRepository();
$accessTokenRepository = new AccessTokenRepository();
$scopeRepository = new ScopeRepository();
$userRepository = new UserRepository();
$refreshTokenRepository = new RefreshTokenRepository();
$privateKeyPath = 'file://' . __DIR__ . '/../private.key';
$publicKeyPath = 'file://' . __DIR__ . '/../public.key';
// Setup the authorization server // Setup the authorization server
$server = new AuthorizationServer( $server = new AuthorizationServer(
$clientRepository, new ClientRepository(), // instance of ClientRepositoryInterface
$accessTokenRepository, new AccessTokenRepository(), // instance of AccessTokenRepositoryInterface
$scopeRepository, new ScopeRepository(), // instance of ScopeRepositoryInterface
$privateKeyPath, 'file://'.__DIR__.'/../private.key', // path to private key
$publicKeyPath 'file://'.__DIR__.'/../public.key' // path to public key
); );
$grant = new PasswordGrant(
new UserRepository(), // instance of UserRepositoryInterface
new RefreshTokenRepository() // instance of RefreshTokenRepositoryInterface
);
$grant->setRefreshTokenTTL(new \DateInterval('P1M')); // refresh tokens will expire after 1 month
// Enable the password grant on the server with a token TTL of 1 hour // Enable the password grant on the server with a token TTL of 1 hour
$server->enableGrantType( $server->enableGrantType(
new PasswordGrant($userRepository, $refreshTokenRepository), $grant,
new \DateInterval('PT1H') new \DateInterval('PT1H') // access tokens will expire after 1 month
); );
return $server; return $server;
}, },
]); ]);
$app->post('/access_token', function (ServerRequestInterface $request, ResponseInterface $response) use ($app) { $app->post(
/* @var \League\OAuth2\Server\AuthorizationServer $server */ '/access_token',
$server = $app->getContainer()->get(AuthorizationServer::class); function (ServerRequestInterface $request, ResponseInterface $response) use ($app) {
try { /* @var \League\OAuth2\Server\AuthorizationServer $server */
return $server->respondToAccessTokenRequest($request, $response); $server = $app->getContainer()->get(AuthorizationServer::class);
} catch (OAuthServerException $exception) {
return $exception->generateHttpResponse($response);
} catch (\Exception $exception) {
$body = new Stream('php://temp', 'r+');
$body->write($exception->getMessage());
return $response->withStatus(500)->withBody($body); try {
// Try to respond to the access token request
return $server->respondToAccessTokenRequest($request, $response);
} catch (OAuthServerException $exception) {
// All instances of OAuthServerException can be converted to a PSR-7 response
return $exception->generateHttpResponse($response);
} catch (\Exception $exception) {
// Catch unexpected exceptions
$body = $response->getBody();
$body->write($exception->getMessage());
return $response->withStatus(500)->withBody($body);
}
} }
}); );
$app->run(); $app->run();