Updated password grant example

This commit is contained in:
Alex Bilbie 2015-11-16 12:58:50 +00:00
parent e7e4892408
commit bb17abfe26
2 changed files with 39 additions and 20 deletions

View File

@ -1,34 +1,50 @@
<?php
use League\OAuth2\Server\Exception\OAuthException;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Grant\PasswordGrant;
use League\OAuth2\Server\Server;
use OAuth2ServerExamples\Repositories\AccessTokenRepository;
use OAuth2ServerExamples\Repositories\ClientRepository;
use OAuth2ServerExamples\Repositories\ScopeRepository;
use OAuth2ServerExamples\Repositories\UserRepository;
use Symfony\Component\HttpFoundation\Request;
use Slim\App;
use Slim\Http\Request;
use Slim\Http\Response;
include(__DIR__ . '/../vendor/autoload.php');
// Setup the authorization server
$server = new Server();
$server->addRepository(new ClientRepository());
$server->addRepository(new ScopeRepository());
$server->addRepository(new AccessTokenRepository());
$server->addRepository(new UserRepository());
// Enable the password grant
$server->enableGrantType('PasswordGrant');
// Init our repositories
$clientRepository = new ClientRepository();
$scopeRepository = new ScopeRepository();
$accessTokenRepository = new AccessTokenRepository();
$userRepository = new UserRepository();
// Setup app + routing
$application = new \Proton\Application();
$application->post('/access_token', function (Request $request) use ($server) {
// Enable the client credentials grant on the server
$server->enableGrantType(new PasswordGrant(
$userRepository,
$clientRepository,
$scopeRepository,
$accessTokenRepository
));
// App
$app = new App([Server::class => $server]);
$app->post('/access_token', function (Request $request, Response $response) {
/** @var Server $server */
$server = $this->getContainer()->get(Server::class);
try {
return $server->getAccessTokenResponse($request);
} catch (OAuthException $e) {
return $server->respondToRequest($request);
} catch (OAuthServerException $e) {
return $e->generateHttpResponse();
} catch (\Exception $e) {
return $response->withStatus(500)->write($e->getMessage());
}
});
// Run the app
$application->run();
$app->run();

View File

@ -1,22 +1,25 @@
<?php
namespace OAuth2ServerExamples\Repositories;
use League\OAuth2\Server\Entities\Interfaces\UserEntityInterface;
use League\OAuth2\Server\Repositories\UserRepositoryInterface;
use OAuth2ServerExamples\Entities\UserEntity;
class UserRepository implements UserRepositoryInterface
{
/**
* Get a user
* Get a user entity
*
* @param string $username
* @param string $password
*
* @return UserEntityInterface
* @return \League\OAuth2\Server\Entities\Interfaces\UserEntityInterface
*/
public function getByCredentials($username, $password)
public function getUserEntityByUserCredentials($username, $password)
{
if ($username === 'alex' && $password === 'whisky') {
return new UserEntity();
}
return null;
}
}