mehdibo/oauth2-fortytwo

PHP League OAuth 2.0 客户端的 42 内部网 OAuth 2.0 支持

v1.0.1 2022-08-10 16:06 UTC

This package is auto-updated.

Last update: 2024-09-10 20:20:56 UTC


README

Latest Stable Version Latest Unstable Version Software License Unit tests Packagist Downloads

本软件包为 PHP League 的 OAuth 2.0 客户端 提供 42 内部网的 OAuth 2.0 支持。

安装

使用 composer 安装

composer require mehdibo/oauth2-fortytwo

用法

与 Symfony 一起使用

您可以使用此库与 knpuniversity/oauth2-client-bundle 一起使用

使用 composer 安装 knpuniversity/oauth2-client-bundle

composer require knpuniversity/oauth2-client-bundle

安装 mehdibo/oauth2-fortytwo

composer require mehdibo/oauth2-fortytwo

将这些行添加到您的 .env 文件中

###> mehdibo/oauth2-fortytwo ###
OAUTH_FT_ID=
OAUTH_FT_SECRET=
###< mehdibo/oauth2-fortytwo ###

通过更新 config/packages/knpu_oauth2_client.yml 配置软件包以使用 FT 的客户端

knpu_oauth2_client:
    clients:
        forty_two:
            type: generic
            provider_class: Mehdibo\OAuth2\Client\Provider\FortyTwo
            client_id: '%env(OAUTH_FT_ID)%'
            client_secret: '%env(OAUTH_FT_SECRET)%'
            redirect_route: auth_social_fortytwo_check # Here is the name of the route that will be used to check the code

创建控制器以处理认证逻辑,更多详情请查看 这里

# src/Controller/FortyTwoController.php

namespace App\Controller;

use ApiPlatform\Core\OpenApi\Model\Operation;
use ApiPlatform\Core\OpenApi\Model\PathItem;
use ApiPlatform\Core\OpenApi\OpenApi;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class FortyTwoController extends AbstractController
{

    #[Route('/auth/login/fortytwo', name: 'auth_social_fortytwo_start')]
    public function connect(ClientRegistry $clientRegistry): RedirectResponse
    {
        return $clientRegistry
            ->getClient('forty_two')
            ->redirect([], []);
    }

    #[Route('/auth/login/fortytwo/check', name: 'auth_social_fortytwo_check')]
    public function connectCheck(Request $request, ClientRegistry $clientRegistry): void
    {
        throw new \LogicException("This should be caught by the guard authenticator");
    }
}

最后一步是创建一个认证守卫

授权码流程

$provider = new \Mehdibo\OAuth2\Client\Provider\FortyTwo([
    'clientId'          => '{uid}',
    'clientSecret'      => '{secret}',
    'redirectUri'       => '{redirect-uri}',
]);

if (!isset($_GET['code'])) {

    // If we don't have an authorization code then get one
    $authUrl = $provider->getAuthorizationUrl();
    $_SESSION['oauth2state'] = $provider->getState();
    header('Location: '.$authUrl);
    exit;

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {

    unset($_SESSION['oauth2state']);
    exit('Invalid state');

} else {

    // Try to get an access token (using the authorization code grant)
    $token = $provider->getAccessToken('authorization_code', [
        'code' => $_GET['code']
    ]);

    // Optional: Now you have a token you can look up a users profile data
    try {

        // We got an access token, let's now get the user's details
        /**
         * @var $user \Mehdibo\OAuth2\Client\Provider\ResourceOwner
        */
        $user = $provider->getResourceOwner($token);

        // Use these details to create a new profile
        printf('Hello %s!', $user->getLogin());

    } catch (Exception $e) {

        // Failed to get user details
        exit('Oh dear...');
    }

    // Use this to interact with an API on the users behalf
    echo $token->getToken();
}

管理作用域

您可以通过将它们传递给 getAuthorizationUrl() 方法来添加额外的作用域

$options = [
    'scope' => ['public','profile','projects']
];

$authorizationUrl = $provider->getAuthorizationUrl($options);

如果没有传递作用域,则只使用 public

测试

$ ./vendor/bin/phpunit