项目作者: wohali

项目描述 :
New Discord Provider for the OAuth 2.0 Client
高级语言: PHP
项目地址: git://github.com/wohali/oauth2-discord-new.git
创建时间: 2017-10-15T07:15:21Z
项目社区:https://github.com/wohali/oauth2-discord-new

开源协议:MIT License

下载


Discord Provider for OAuth 2.0 Client

Source Code
Latest Version
Software License
Build Status
Scrutinizer
Coverage Status
Total Downloads

This package provides Discord OAuth 2.0 support for the PHP League’s OAuth 2.0 Client, v2.0 and up.

Requirements

The following versions of PHP are supported.

  • PHP 7.2
  • PHP 7.3
  • PHP 7.4
  • PHP 8.0
  • PHP 8.1
  • PHP 8.2

Installation

To install, use composer:

  1. $ composer require wohali/oauth2-discord-new

Usage

Usage is the same as The League’s OAuth client, using \Wohali\OAuth2\Client\Provider\Discord as the provider.

Sample Authorization Code Flow

This self-contained example:

  1. Gets an authorization code
  2. Gets an access token using the provided authorization code
  3. Looks up the user’s profile with the provided access token

You can try this script by registering a Discord App with a redirect URI to your server’s copy of this sample script. Then, place the Discord app’s client id and secret, along with that same URI, into the settings at the top of the script.

  1. <?php
  2. require __DIR__ . '/vendor/autoload.php';
  3. session_start();
  4. echo ('Main screen turn on!<br/><br/>');
  5. $provider = new \Wohali\OAuth2\Client\Provider\Discord([
  6. 'clientId' => '{discord-client-id}',
  7. 'clientSecret' => '{discord-client-secret}',
  8. 'redirectUri' => '{your-server-uri-to-this-script-here}'
  9. ]);
  10. if (!isset($_GET['code'])) {
  11. // Step 1. Get authorization code
  12. $authUrl = $provider->getAuthorizationUrl();
  13. $_SESSION['oauth2state'] = $provider->getState();
  14. header('Location: ' . $authUrl);
  15. // Check given state against previously stored one to mitigate CSRF attack
  16. } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
  17. unset($_SESSION['oauth2state']);
  18. exit('Invalid state');
  19. } else {
  20. // Step 2. Get an access token using the provided authorization code
  21. $token = $provider->getAccessToken('authorization_code', [
  22. 'code' => $_GET['code']
  23. ]);
  24. // Show some token details
  25. echo '<h2>Token details:</h2>';
  26. echo 'Token: ' . $token->getToken() . "<br/>";
  27. echo 'Refresh token: ' . $token->getRefreshToken() . "<br/>";
  28. echo 'Expires: ' . $token->getExpires() . " - ";
  29. echo ($token->hasExpired() ? 'expired' : 'not expired') . "<br/>";
  30. // Step 3. (Optional) Look up the user's profile with the provided token
  31. try {
  32. $user = $provider->getResourceOwner($token);
  33. echo '<h2>Resource owner details:</h2>';
  34. printf('Hello %s#%s!<br/><br/>', $user->getUsername(), $user->getDiscriminator());
  35. var_export($user->toArray());
  36. } catch (Exception $e) {
  37. // Failed to get user details
  38. exit('Oh dear...');
  39. }
  40. }

Managing Scopes

When creating your Discord authorization URL in Step 1, you can specify the state and scopes your application may authorize.

  1. $options = [
  2. 'state' => 'OPTIONAL_CUSTOM_CONFIGURED_STATE',
  3. 'scope' => ['identify', 'email', '...'] // array or string
  4. ];
  5. $authorizationUrl = $provider->getAuthorizationUrl($options);

If neither are defined, the provider will utilize internal defaults.

At the time of authoring this documentation, the following scopes are available:

  • bot
  • connections
  • email
  • identify
  • guilds
  • guilds.join
  • gdm.join
  • messages.read
  • rpc
  • rpc.api
  • rpc.notifications.read
  • webhook.incoming

Refreshing a Token

You can refresh an expired token using a refresh token rather than going through the entire process of obtaining a brand new token. To do so, simply reuse the fresh token from your data store to request a refresh:

  1. // create $provider as in the initial example
  2. $existingAccessToken = getAccessTokenFromYourDataStore();
  3. if ($existingAccessToken->hasExpired()) {
  4. $newAccessToken = $provider->getAccessToken('refresh_token', [
  5. 'refresh_token' => $existingAccessToken->getRefreshToken()
  6. ]);
  7. // Purge old access token and store new access token to your data store.
  8. }

Client Credentials Grant

Discord provides a client credentials flow for bot developers to get their own bearer tokens for testing purposes. This returns an access token for the bot owner:

  1. // create $provider as in the initial example
  2. try {
  3. // Try to get an access token using the client credentials grant.
  4. $accessToken = $provider->getAccessToken('client_credentials');
  5. } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
  6. // Failed to get the access token
  7. exit($e->getMessage());
  8. }

Bot Authorization

To authorize a bot, specify a scope of bot and set permissions appropriately:

  1. // create $provider as in the initial example
  2. $options = [
  3. 'scope' => ['bot'],
  4. 'permissions' => 1
  5. ];
  6. $authorizationUrl = $provider->getAuthorizationUrl($options);
  7. // Redirect user to authorization page
  8. header('Location: ' . $authUrl);

Testing

  1. $ ./vendor/bin/parallel-lint src test
  2. $ ./vendor/bin/phpcs src --standard=psr2 -sp
  3. $ ./vendor/bin/phpunit --coverage-text

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.