Skip to content

Instantly share code, notes, and snippets.

@mpociot
Last active February 21, 2018 00:52
Show Gist options
  • Save mpociot/4b55cd0af2227c6cc3283e7305430e7b to your computer and use it in GitHub Desktop.
Save mpociot/4b55cd0af2227c6cc3283e7305430e7b to your computer and use it in GitHub Desktop.
Validate access tokens sent through Amazon Alexa requests
<?php
/*
* Example usage
*/
$botman->middleware->received(new CheckAccessToken());
$botman->hears('MyIntent', function (BotMan $bot) {
$user = $bot->getMessage()->getExtras('user');
return $bot->reply('Hello, '.$user->name, [
'shouldEndSession' => true
]);
});
<?php
namespace App\BotMan\Middleware;
use BotMan\BotMan\BotMan;
use Laravel\Passport\TokenRepository;
use League\OAuth2\Server\ResourceServer;
use Symfony\Component\HttpFoundation\Request;
use BotMan\Drivers\AmazonAlexa\Extensions\Card;
use BotMan\BotMan\Interfaces\Middleware\Received;
use BotMan\BotMan\Messages\Incoming\IncomingMessage;
use BotMan\BotMan\Messages\Outgoing\OutgoingMessage;
use League\OAuth2\Server\Exception\OAuthServerException;
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
class CheckAccessToken implements Received
{
const LINK_ACCOUNT_MESSAGE = 'Please link your account in your Alexa app.';
/**
* Handle an incoming message.
*
* @param IncomingMessage $message
* @param callable $next
* @param BotMan $bot
*
* @return mixed
*/
public function received(IncomingMessage $message, $next, BotMan $bot)
{
/*
* Get TokenRepository and ResourceServer from the IoC
*/
$tokens = app(TokenRepository::class);
$server = app(ResourceServer::class);
$tokenString = array_get($message->getPayload(), 'session.user.accessToken');
/*
* Create a Symfony request to simulate an incoming request.
*/
$request = Request::create('/', 'GET', [], [], [], ['HTTP_AUTHORIZATION' => 'Bearer '.$tokenString]);
/*
* Convert the Symfony request to a PSR compliant request and validate it manually
*/
$request = (new DiactorosFactory)->createRequest($request);
try {
$psr = $server->validateAuthenticatedRequest($request);
} catch (OAuthServerException $exception) {
$reply = OutgoingMessage::create(self::LINK_ACCOUNT_MESSAGE)->withAttachment(Card::create(null)->type('LinkAccount'));
return $bot->reply($reply);
}
/*
* Next, retrieve the token for this JWT and store the user to the incoming message.
*/
$token = $tokens->find(
$psr->getAttribute('oauth_access_token_id')
);
$message->addExtras('user', $token->user);
return $next($message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment