fruitcake/oauth2-rooiontmoet

RooiOntmoet OAuth 2.0 客户端提供商,用于 PHP League 的 OAuth 2.0 客户端

dev-master / 1.0.x-dev 2016-02-25 13:31 UTC

This package is auto-updated.

Last update: 2024-09-11 09:34:19 UTC


README

此包为 PHP League 的 OAuth 2.0 客户端 提供RooiOntmoet OAuth 2.0 支持。

要求

  • PHP 5.5 或更高版本

安装

使用 Composer 安装此包

composer require fruitcake/oauth2-rooiontmoet:"~1.0@dev"

在开发过程中,需要使用 @dev 标志。

使用方法

可用作用域

  • profile: 默认公开资料(全名 + ID)
  • email: 用户电子邮件

您需要申请 API 访问。默认情况下,仅授予 profile 访问权限。管理员用户可以访问更多作用域,具体取决于访问级别。请联系 Fruitcake 获取更多信息。

只有经过验证的端点才有访问权限,因此请确保您首先注册这些端点!

授权码流程

require __DIR__ .'/../vendor/autoload.php';

session_start();

// Create Provider
$provider = new RooiOntmoet\OAuth2\Client\Provider\RooiOntmoet([
  'clientId'          => 'my-client-id',
  'clientSecret'      => 'my-client-secret',
  'redirectUri'       => 'http://my-domain.com/login-callback.php',
]);

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

    // If we don't have an authorization code then get one
    $authUrl = $provider->getAuthorizationUrl([
      'scope' => ['profile', 'email']
    ]);
        
    $_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
        $user = $provider->getResourceOwner($token);

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

        echo '<pre>';

        // Use this to save the user information
        print_r($user->toArray());

        // Use this to interact with an API on the users behalf
        var_dump($token->getToken());
        # string(217) "CAADAppfn3msBAI7tZBLWg...

        // Number of seconds until the access token will expire, and need refreshing
        var_dump($token->getExpires());
        # int(1436825866)

        echo '</pre>';
    } catch (Exception $e) {

        // Failed to get user details
        exit('Oh dear...' . $e->getMessage());
    }

}

RooiOntmoetUser 实体

当使用 getResourceOwner() 方法获取用户节点时,它将以 RooiOntmoetUser 实体的形式返回。

$user = $provider->getResourceOwner($token);

$id = $user->getId();
var_dump($id);
# string(1) "4"

$name = $user->getName();
var_dump($name);
# string(15) "First Last"

# Requires the "email" scope
$email = $user->getEmail();
var_dump($email);
# string(15) "user@example.com"

您也可以使用 toArray() 方法以纯 PHP 数组的形式获取用户节点的所有数据。

$userData = $user->toArray();

客户端凭证流程

您可以使用客户端凭证流程在您的应用程序中直接发起请求,而不需要请求许可。这将代表您的客户端操作,并且仅在您有权访问给定作用域时才可用。

// Create Provider
$provider = new RooiOntmoet\OAuth2\Client\Provider\RooiOntmoet([
  'clientId' => 'my-client-id',
  'clientSecret' => 'my-client-secret',
]);

try {
    // Try to get an access token using the client credentials grant.
    $token = $provider->getAccessToken('client_credentials', [
      'scope' => 'allusers',
    ]);

    $request = $provider->getAuthenticatedRequest('GET', $provider->baseResourceUrl . '/users', $token);
    $response = $provider->getHttpClient()->send($request);
    $result = json_decode($response->getBody(), true);

    dd($result);

} catch (\Exception $e) {

    // Failed to get the access token
    exit($e->getMessage());

}

Laravel Socialite 驱动程序

您可以使用 Socialite 提供商在 Laravel 中启用简单的 OAuth。只需在 ServiceProvider 中添加驱动程序即可。

$socialite = $this->app->make('Laravel\Socialite\Contracts\Factory');
$socialite->extend(
    'rooiontmoet',
    function ($app) use ($socialite) {
        $config = [
              'client_id' => 'client1id',
              'client_secret' => 'client1secret',
              'redirect' => '',
          ];

        $provider = $socialite->buildProvider('RooiOntmoet\OAuth2\Client\Socialite\RooiOntmoet', $config);
        $provider = $provider->scopes(['public', 'email']);

        return $provider;
    }
);