public
Last active

Implementing Twitter sign-in with Silex and PHP

  • Download Gist
index.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
<?php
define('CONS_KEY', 'Application consumer key');
define('CONS_SECRET', 'Application consumer secret');
 
require_once __DIR__.'/silex.phar';
 
$app = new Silex\Application();
 
// register the session extension
$app->register(new Silex\Extension\SessionExtension());
 
$app->get('/', function() use($app) {
$username = $app['session']->get('username');
 
if ($username == null) {
return 'Welcome Guest. <a href="/login">Login</a>';
} else {
return 'Welcome ' . $app->escape($username);
}
});
 
$app->get('/login', function () use ($app) {
// check if the user is already logged-in
if (null !== ($username = $app['session']->get('username'))) {
return $app->redirect('/');
}
 
$oauth = new OAuth(CONS_KEY, CONS_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$request_token = $oauth->getRequestToken('https://twitter.com/oauth/request_token');
 
$app['session']->set('secret', $request_token['oauth_token_secret']);
 
return $app->redirect('https://twitter.com/oauth/authenticate?oauth_token=' . $request_token['oauth_token']);
});
 
$app->get('/auth', function() use ($app) {
// check if the user is already logged-in
if (null !== ($username = $app['session']->get('username'))) {
return $app->redirect('/');
}
 
$oauth_token = $app['request']->get('oauth_token');
 
if ($oauth_token == null) {
$app->abort(400, 'Invalid token');
}
 
$secret = $app['session']->get('secret');
 
$oauth = new OAuth(CONS_KEY, CONS_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken($oauth_token, $secret);
 
try {
$oauth_token_info = $oauth->getAccessToken('https://twitter.com/oauth/access_token');
} catch (OAuthException $e) {
$app->abort(401, $e->getMessage());
}
 
// retrieve Twitter user details
$oauth->setToken($oauth_token_info['oauth_token'], $oauth_token_info['oauth_token_secret']);
$oauth->fetch('https://twitter.com/account/verify_credentials.json');
$json = json_decode($oauth->getLastResponse());
 
$app['session']->set('username', $json->screen_name);
 
return $app->redirect('/');
});
 
$app->run();

For anyone else landing here, the corresponding blog post to this.

Thanks for the code - very helpful.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.