【问题标题】:How to use Silex authorization with OpenID?如何通过 OpenID 使用 Silex 授权?
【发布时间】:2013-10-22 17:25:25
【问题描述】:

我正在尝试将 OpenID 集成到我的 Silex 应用程序中,但我不确定如何将其连接到 Silex's authorization service provider。看起来他们已经捆绑了身份验证和授权,我不是很热衷。

到目前为止我得到了什么:

首先,我使用LightOpenID 生成一个 OpenID 登录 URL,并将其注入到我的 Twig 模板中:

$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()));
});

并将其渲染为我的 Twig 布局的一部分:

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

当您单击该链接时,Google 会进行身份验证并将您发送回此处:

$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');

我被困在哪里:

我如何登录用户以便我可以利用 Silex/Symfony 的安全“防火墙”?我想将我网站的 /admin 部分限制为仅限某些用户使用,并且我不想自己实现整个 ACL 机制。

【问题讨论】:

标签: php authorization openid acl silex


【解决方案1】:

您可以使用 LightOpenID 实现自己的身份验证提供程序,也可以在验证身份后设置会话变量并依靠它来验证您的用户。

看看这个实现https://github.com/KnpLabs/marketplace/blob/master/src/Marketplace/Provider/Service/Security.php 以获取第二种方法的示例。

【讨论】:

  • 这比我想象的要简单得多,谢谢你的例子! $app-&gt;get 返回什么样的对象?我可以向它添加一些方法,例如 -&gt;restrict('ROLE'),我可以在 before 方法中检查这些方法吗?
  • 没关系,我想我应该可以通过提供custom route class 来做到这一点。感谢您的帮助。
  • 这将起作用,并且将来会更灵活地适应!
猜你喜欢
  • 2021-03-05
  • 2022-10-15
  • 2021-11-04
  • 1970-01-01
  • 2020-10-08
  • 1970-01-01
  • 2021-12-16
  • 2018-11-13
  • 1970-01-01
相关资源
最近更新 更多