dotkernel/dot-auth-social

社交提供商的认证包装器

1.2.3 2024-07-03 09:44 UTC

This package is auto-updated.

Last update: 2024-09-03 10:08:47 UTC


README

dot-auth-social 是基于 thephpleague/oauth2-client 社交提供商的包装器。

OSS Lifecycle

dot-auth-social 徽章

OSS Lifecycle PHP from Packagist (specify version)

GitHub issues GitHub forks GitHub stars GitHub license

Build Static codecov

SymfonyInsight

要求

  • PHP >= 8.1

安装

在您的项目目录中运行以下命令

$ composer require dotkernel/dot-auth-social

安装后,将 ConfigProvider 类添加到您的配置聚合中。

config/autoload 中创建一个新的文件 social-authentication.global.php,内容如下

return [
    'social_authentication' => [
        'facebook' => [
            'client_id' => '',
            'client_secret' => '',
            'redirect_uri' => '',
            'graph_api_version' => '',
        ]
    ]
];

注意:不要忘记在数组中放置您的凭证

用法

在此示例中,我们将创建一个新的控制器,但您也可以使用现有的控制器。

<?php

namespace Frontend\User\Controller;

use Dot\Controller\AbstractActionController;
use Dot\AuthSocial\Service\AuthenticationServiceInterface;
use Laminas\Diactoros\Response\RedirectResponse;
use Psr\Http\Message\ResponseInterface;

class FacebookController extends AbstractActionController
{
    private AuthenticationServiceInterface $service;

    public function __construct(AuthenticationServiceInterface $service)
    {
        $this->service = $service;
    }

    public function authAction(): ResponseInterface
    {
        $code = $this->request->getQueryParams()['code'] ?? false;
        if (! $code) {
            return new RedirectResponse($this->service->getAuthorizationUrl());
        }

        $result = $this->service->authenticate($code);
        if (! $result->isValid()) {
            // invalid authentication, check $result->getMessages() for errors.
        } else {
            // valid authentication, use $result->getArrayCopy() to get the user details
        }
    }
}

为控制器创建一个工厂

<?php

use Dot\AuthSocial\Service\FacebookService;
use Psr\Container\ContainerInterface;

class FacebookControllerFactory
{
    public function __invoke(ContainerInterface $container): FacebookController
    {
        return new FacebookController($container->get(FacebookService::class));
    }
}

确保在 ConfigProvider 中注册您的控制器与工厂。