Question

I'm trying to integrate OpenID into my Silex application, but I'm unsure how to hook it into Silex's authorization service provider. It looks like they've bundled authentication and authorization, which I'm not super keen on.

What I've got so far:

First I generate an OpenID login URL using LightOpenID and inject it into my Twig templates:

$app['openid'] = $app->share(function (Application $app) {
    $openid = new \LightOpenID($app['request']->getHttpHost());
    $openid->identity = 'https://www.google.com/accounts/o8/id';
    $openid->returnUrl = $app->url('check_openid', array('returnUrl' => $app['request']->get('returnUrl', $app['request']->getRequestUri())));
    return $openid;
});

$app->before(function (Request $request) use ($app) {
    // todo: check if user is logged in, if not generate OpenID login url
    $app['twig']->addGlobal('openid', array('authUrl' => $app['openid']->authUrl()));
});

And render that as part of my Twig layout:

<a href="{{ openid.authUrl }}" class="btn btn-google-plus btn-xs" type="button"><i class="icon-google-plus"></i> Sign in with Google</a>

When you click that link, Google does the authentication and sends you back here:

$app->get('/login/openid', function (Request $request) use ($app) {
    if(!$app['openid']->mode) {
        return $app->redirect($app['openid']->authUrl(), 303);
    } elseif($app['openid']->mode === 'cancel') {
        // TODO: redirect user back to login page w/ error message
        die('User has canceled authentication!');
    } elseif($app['openid']->validate()) {
        // TODO: log user in (set session variables)
        return $app->redirect($request->get('returnUrl', $app->path('home')), 303);
    } else {
        throw new Exception('User could not be validated');
    }
})->bind('check_openid');

Where I'm stuck:

How do I log the user in such that I can take advantage of Silex/Symfony's security "firewalls"? I want to limit the /admin section of my site to only certain users and I don't want to implement a whole ACL mechanism myself.

Was it helpful?

Solution

You can either implement your own Authentication Provider using LightOpenID or you can set the session variables once you validate the Identity and rely on that to authenticate your users.

Take a look at this implementation https://github.com/KnpLabs/marketplace/blob/master/src/Marketplace/Provider/Service/Security.php for an example of the second method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top