### Install league/oauth2-server via Composer Source: https://github.com/thephpleague/oauth2-server/wiki/Securing-your-API-with-OAuth-2.0 Demonstrates how to add the league/oauth2-server library to your project's composer.json file and install it using Composer. This is the recommended installation method. ```JSON { "require": { "league/oauth2-server": "2.*" } } ``` -------------------------------- ### Install League OAuth2 Server via Composer Source: https://github.com/thephpleague/oauth2-server/wiki/Developing-an-OAuth-2.0-authorization-server This snippet shows how to add the league/oauth2-server dependency to your project's composer.json file and install it using Composer. It covers both adding to an existing composer.json and creating a new one. ```JSON { "require": { "league/oauth2-server": "2.*" } } ``` -------------------------------- ### Install league/oauth2-server using Composer Source: https://github.com/thephpleague/oauth2-server/blob/master/README.md This command installs the league/oauth2-server package using Composer, the dependency manager for PHP. Ensure Composer is installed and accessible in your environment. ```bash composer require league/oauth2-server ``` -------------------------------- ### Integrate league/oauth2-server with PDO Storage Source: https://github.com/thephpleague/oauth2-server/wiki/Securing-your-API-with-OAuth-2.0 Shows how to initialize the OAuth2 server with PDO storage models for database interaction. It includes setting up a database connection and instantiating the server with the session storage. ```PHP // Initiate the Request handler $request = new League\OAuth2\Server\Util\Request(); // Initiate a new database connection $db = new League\OAuth2\Server\Storage\PDO\Db('mysql:host=localhost;dbname=oauth'); // Initiate the auth server with the models $server = new League\OAuth2\Server\Resource( new League\OAuth2\Server\Storage\PDO\Session($db) ); ``` -------------------------------- ### Injecting Implementations into Authorization Server Source: https://github.com/thephpleague/oauth2-server/wiki/Implementing-the-storage-interfaces This snippet demonstrates how to instantiate and inject the required OAuthClient, OAuthSession, and OAuthScope implementations into the League\OAuth2\Server\Authorization server. ```PHP isValid(); } // The access token is missing or invalid... catch (League\OAuth2\Server\Exception\InvalidAccessTokenException $e) { $app = \Slim\Slim::getInstance(); $res = $app->response(); $res['Content-Type'] = 'application/json'; $res->status(403); $res->body(json_encode(array( 'error' => $e->getMessage() ))); } }; }; ``` -------------------------------- ### Initialize OAuth2 Server Controller Source: https://github.com/thephpleague/oauth2-server/wiki/Developing-an-OAuth-2.0-authorization-server This snippet shows how to initialize the OAuth2 server within a controller's constructor. It includes setting up the request handler, database connection, and the authorization server with necessary storage models and grant types. ```php public function __construct() { // Initiate the request handler which deals with $_GET, $_POST, etc $request = new League\OAuth2\Server\Util\Request(); // Initiate a new database connection $db = new League\OAuth2\Server\Storage\PDO\Db('mysql:user:pass@localhost/oauth'); // Create the auth server, the three parameters passed are references // to the storage models $this->authserver = new League\OAuth2\Server\Authorization( new ClientModel, new SessionModel, new ScopeModel ); // Enable the authorization code grant type $this->authserver->addGrantType(new League\OAuth2\Server\Grant\AuthCode()); } ``` -------------------------------- ### Test Device Authorization Grant Source: https://github.com/thephpleague/oauth2-server/blob/master/examples/README.md This snippet shows the initial cURL request for the device authorization grant to obtain a device code. It requires the client ID, client secret, and scope. ```Shell curl -X "POST" "http://localhost:4444/device_code.php/device_authorization" \ -H "Content-Type: application/x-www-form-urlencoded" \ -H "Accept: 1.0" \ --data-urlencode "client_id=myawesomeapp" \ --data-urlencode "client_secret=abc123" \ --data-urlencode "scope=basic email" ``` -------------------------------- ### Get User Information with Access Token Source: https://github.com/thephpleague/oauth2-server/wiki/Securing-your-API-with-OAuth-2.0 This PHP code snippet demonstrates how to create an API endpoint that retrieves user information. It validates an access token and, if valid, returns user details. It conditionally includes email and phone number if the 'user.contact' scope is present in the access token. ```php $app->get('/user/:id', $checkToken(), function ($id) use ($server, $app) { $user_model = new UserModel(); $user = $user_model->getUser($id); if ( ! $user) { $res = $app->response(); $res->status(404); $res['Content-Type'] = 'application/json'; $res->body(json_encode(array( 'error' => 'User not found' ))); } else { // Basic response $response = array( 'error' => null, 'result' => array( 'user_id' => $user['id'], 'firstname' => $user['firstname'], 'lastname' => $user['lastname'] ) ); // If the acess token has the "user.contact" access token include // an email address and phone numner if ($server->hasScope('user.contact')) { $response['result']['email'] = $user['email']; $response['result']['phone'] = $user['phone']; } // Respond $res = $app->response(); $res['Content-Type'] = 'application/json'; $res->body(json_encode($response)); } }); ``` -------------------------------- ### Handle OAuth2 Authorization Request Source: https://github.com/thephpleague/oauth2-server/wiki/Developing-an-OAuth-2.0-authorization-server This code demonstrates how to handle the initial authorization request in an OAuth2 controller. It checks for required parameters, saves them to the session, and redirects the user to a sign-in page. ```php public function action_index() { try { // Tell the auth server to check the required parameters are in the // query string $params = $server->getGrantType('authorization_code')->checkAuthoriseParams(); // Save the verified parameters to the user's session Session::put('client_id', $params['client_id']); Session::put('client_details', $params['client_details']); Session::put('redirect_uri', $params['redirect_uri']); Session::put('response_type', $params['response_type']); Session::put('scopes', $params['scopes']); // Redirect the user to the sign-in route return Redirect::to(‘oauth/signin’); } catch (Oauth2\Exception\ClientException $e) { // Throw an error here which says what the problem is with the // auth params } catch (Exception $e) { // Throw an error here which has caught a non-library specific error } } ``` -------------------------------- ### Exchange Device Code for Access Token Source: https://github.com/thephpleague/oauth2-server/blob/master/examples/README.md This snippet demonstrates the cURL request to exchange a previously obtained device code for an access token. It requires the client ID, client secret, and the device code. ```Shell curl -X "POST" "http://localhost:4444/device_code.php/access_token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -H "Accept: 1.0" \ --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:device_code" \ --data-urlencode "device_code={{DEVICE_CODE}}" \ --data-urlencode "client_id=myawesomeapp" \ --data-urlencode "client_secret=abc123" ``` -------------------------------- ### Test Client Credentials Grant Source: https://github.com/thephpleague/oauth2-server/blob/master/examples/README.md This snippet demonstrates how to test the client credentials grant type using a cURL request. It requires the client ID, client secret, and desired scope. ```Shell curl -X "POST" "http://localhost:4444/client_credentials.php/access_token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -H "Accept: 1.0" \ --data-urlencode "grant_type=client_credentials" \ --data-urlencode "client_id=myawesomeapp" \ --data-urlencode "client_secret=abc123" \ --data-urlencode "scope=basic email" ``` -------------------------------- ### Test Password Grant Source: https://github.com/thephpleague/oauth2-server/blob/master/examples/README.md This snippet shows how to test the password grant type using a cURL request. It requires the client ID, client secret, username, password, and desired scope. ```Shell curl -X "POST" "http://localhost:4444/password.php/access_token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -H "Accept: 1.0" \ --data-urlencode "grant_type=password" \ --data-urlencode "client_id=myawesomeapp" \ --data-urlencode "client_secret=abc123" \ --data-urlencode "username=alex" \ --data-urlencode "password=whisky" \ --data-urlencode "scope=basic email" ``` -------------------------------- ### Handle OAuth2 Authorization Redirection Source: https://github.com/thephpleague/oauth2-server/wiki/Developing-an-OAuth-2.0-authorization-server This code snippet handles the redirection to the authorization route after a user has signed in. It retrieves necessary authorization parameters from the session and checks if the user is authenticated before proceeding. ```php public function action_authorise() { // Retrieve the auth params from the user's session $params['client_id'] = Session::get('client_id'); $params['client_details'] = Session::get('client_details'); $params['redirect_uri'] = Session::get('redirect_uri'); $params['response_type'] = Session::get('response_type'); $params['scopes'] = Session::get('scopes'); // Check that the auth params are all present foreach ($params as $key=>$value) { if ($value === null) { // Throw an error because an auth param is missing - don't // continue any further } } // Get the user ID $params['user_id'] = Session::get('user_id'); // User is not signed in so redirect them to the sign-in route (/oauth/signin) if ($params['user_id'] === null) { ``` -------------------------------- ### Test Refresh Token Grant Source: https://github.com/thephpleague/oauth2-server/blob/master/examples/README.md This snippet demonstrates testing the refresh token grant type via cURL. It requires the client ID, client secret, and a valid refresh token obtained from a previous grant. ```Shell curl -X "POST" "http://localhost:4444/refresh_token.php/access_token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -H "Accept: 1.0" \ --data-urlencode "grant_type=refresh_token" \ --data-urlencode "client_id=myawesomeapp" \ --data-urlencode "client_secret=abc123" \ --data-urlencode "refresh_token={{REFRESH_TOKEN}}" ``` -------------------------------- ### Implement OAuth2 User Sign-in Source: https://github.com/thephpleague/oauth2-server/wiki/Developing-an-OAuth-2.0-authorization-server This snippet outlines the process for handling user sign-in within an OAuth2 controller. It retrieves authorization parameters from the session, validates user credentials, and redirects to the authorization route upon successful sign-in. ```php public function action_signin() { // Retrieve the auth params from the user's session $params['client_id'] = Session::get('client_id'); $params['client_details'] = Session::get('client_details'); $params['redirect_uri'] = Session::get('redirect_uri'); $params['response_type'] = Session::get('response_type'); $params['scopes'] = Session::get('scopes'); // Check that the auth params are all present foreach ($params as $key=>$value) { if ($value === null) { // Throw an error because an auth param is missing - don't // continue any further } } // Process the sign-in form submission if (Input::get('signin') !== null) { try { // Get username $u = Input::get('username'); if ($u === null || trim($u) === '') { throw new Exception('please enter your username.'); } // Get password $p = Input::get('password'); if ($p === null || trim($p) === '') { throw new Exception('please enter your password.'); } // Verify the user's username and password // Set the user's ID to a session } catch (Exception $e) { $params['error_message'] = $e->getMessage(); } } // Get the user's ID from their session $params['user_id'] = Session::get('user_id'); // User is signed in if ($params['user_id'] !== null) { // Redirect the user to /oauth/authorise route return Redirect::to('oauth/authorise'); } // User is not signed in, show the sign-in form else { return View::make('oauth.signin', $params); } } ``` -------------------------------- ### Limit Endpoint to User Owner Type Source: https://github.com/thephpleague/oauth2-server/wiki/Securing-your-API-with-OAuth-2.0 This PHP code snippet shows how to restrict an API endpoint to only be accessible by access tokens owned by users. It checks the owner type of the access token and returns a 403 Forbidden error if it's not a 'user'. If it is a user, it proceeds to fetch and return user information, similar to the previous example. ```php $app->get('/user', $checkToken(), function () use ($server, $app) { $user_model = new UserModel(); // Check the access token's owner is a user if ($server->getOwnerType() === 'user') { // Get the access token owner's ID $userId = $server->getOwnerId(); $user = $user_model->getUser($userId); // If the user can't be found return 404 if ( ! $user) { $res = $app->response(); $res->status(404); $res['Content-Type'] = 'application/json'; $res->body(json_encode(array( 'error' => 'Resource owner not found' ))); } // A user has been found else { // Basic response $response = array( 'error' => null, 'result' => array( 'user_id' => $user['id'], 'firstname' => $user['firstname'], 'lastname' => $user['lastname'] ) ); // If the acess token has the "user.contact" access token include // an email address and phone numner if ($server->hasScope('user.contact')) { $response['result']['email'] = $user['email']; $response['result']['phone'] = $user['phone']; } // Respond $res = $app->response(); $res['Content-Type'] = 'application/json'; $res->body(json_encode($response)); } } // The access token isn't owned by a user else { $res = $app->response(); $res->status(403); $res['Content-Type'] = 'application/json'; $res->body(json_encode(array( 'error' => 'Only access tokens representing users can use this endpoint' ))); } }); ``` -------------------------------- ### Issue OAuth2 Access Token Source: https://github.com/thephpleague/oauth2-server/wiki/Developing-an-OAuth-2.0-authorization-server Handles the issuance of an OAuth2 access token. It attempts to issue the token using the authorization server and returns the response as JSON. Includes error handling for client-specific exceptions and general exceptions, setting appropriate HTTP headers. ```php public function action_access_token() { try { // Tell the auth server to issue an access token $response = $this->authserver->issueAccessToken(); } catch (League\OAuth2\Server\Exception\ClientException $e) { // Throw an exception because there was a problem with the client's request $response = array( 'error' => $this->authserver::getExceptionType($e->getCode()), 'error_description' => $e->getMessage() ); // Set the correct header header($this->authserver::getExceptionHttpHeaders($this->authserver::getExceptionType($e->getCode()))); } catch (Exception $e) { // Throw an error when a non-library specific exception has been thrown $response = array( 'error' => 'undefined_error', 'error_description' => $e->getMessage() ); } header('Content-type: application/json'); echo json_encode($response); } ``` -------------------------------- ### Handle OAuth2 Authorization Request Source: https://github.com/thephpleague/oauth2-server/wiki/Developing-an-OAuth-2.0-authorization-server Processes an OAuth2 authorization request, checking for automatic approval or user consent. It generates an authorization code and redirects the user back to the client application with the code or an error message if denied. If the client is not auto-approved and the user has not yet responded, it displays an authorization form. ```php // Check if the client should be automatically approved $autoApprove = ($params['client_details']['auto_approve'] === '1') ? true : false; // Process the authorise request if the user's has clicked 'approve' or the client if (Input::get('approve') !== null || $autoApprove === true) { // Generate an authorization code $code = $server->getGrantType('authorization_code')->newAuthoriseRequest('user', $params['user_id'], $params); // Redirect the user back to the client with an authorization code return Redirect::to( League\OAuth2\Server\Util\RedirectUri::make($params['redirect_uri'], array( 'code' => $code, 'state' => isset($params['state']) ? $params['state'] : '' ) )); } // If the user has denied the client so redirect them back without an authorization code if (Input::get('deny') !== null) { return Redirect::to( League\OAuth2\Server\Util\RedirectUri::make($params['redirect_uri'], array( 'error' => 'access_denied', 'error_message' => $this->authserver->getExceptionMessage('access_denied'), 'state' => isset($params['state']) ? $params['state'] : '' ) )); } // The client shouldn't automatically be approved and the user hasn't yet // approved it so show them a form return View::make('oauth.authorise', $params); ``` -------------------------------- ### Limit Endpoint by Owner Type and Scope in PHP Source: https://github.com/thephpleague/oauth2-server/wiki/Securing-your-API-with-OAuth-2.0 This PHP code snippet demonstrates how to secure an API endpoint using thephpleague/oauth2-server. It restricts access to tokens owned by 'client' and possessing the 'users.list' scope. It also conditionally includes user contact details if the 'user.contact' scope is present. ```php $app->get('/users', $checkToken(), function () use ($server, $app) { $user_model = new UserModel(); $users = $user_model->getUsers(); // Check the access token owner is a client if ($server->getOwnerType() === 'client' && $server->hasScope('users.list')) { $response = array( 'error' => null, 'results' => array() ); $i = 0; foreach ($users as $k => $v) { // Basic details $response['results'][$i]['user_id'] = $v['id']; $response['results'][$i]['firstname'] = $v['firstname']; $response['results'][$i]['lastname'] = $v['lastname']; // Include additional details with the right scope if ($server->hasScope('user.contact')) { $response['results'][$i]['email'] = $v['email']; $response['results'][$i]['phone'] = $v['phone']; } $i++; } $res = $app->response(); $res['Content-Type'] = 'application/json'; $res->body(json_encode($response)); } // Access token owner isn't a client or doesn't have the correct scope else { $res = $app->response(); $res->status(403); $res['Content-Type'] = 'application/json'; $res->body(json_encode(array( 'error' => 'Only access tokens representing clients can use this endpoint' ))); } }); ``` -------------------------------- ### Run PHPUnit Tests for league/oauth2-server Source: https://github.com/thephpleague/oauth2-server/blob/master/README.md This command executes the unit tests for the league/oauth2-server library using PHPUnit. It helps verify the integrity and correctness of the implemented OAuth 2.0 server functionalities. ```bash vendor/bin/phpunit ``` -------------------------------- ### Instantiate PDO Factory with Configuration Array Source: https://github.com/thephpleague/oauth2-server/wiki/Using-the-PDO-storage-classes This code snippet demonstrates how to create an instance of the PDO factory class using an array of database connection parameters. It includes details for username, password, database name, socket path, and database type. ```php 'dbuser', 'password' => 'dbpass', 'database' => 'oauth', 'socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'type' => 'mysql' )); ?> ``` -------------------------------- ### Instantiate PDO Factory with DSN String Source: https://github.com/thephpleague/oauth2-server/wiki/Using-the-PDO-storage-classes This code snippet shows how to instantiate the PDO factory class using a Data Source Name (DSN) string. The DSN includes the database type, host, and database name, along with user credentials. ```php ``` -------------------------------- ### Create Session for Access Token (PHP) Source: https://github.com/thephpleague/oauth2-server/wiki/Creating-custom-grants Illustrates the process of creating a new session for a client and associating it with an owner (user or client). This session is used to manage access tokens. ```php $sessionId = $this->authServer->getStorage('session')->createSession($authParams['client_id'], 'OWNER TYPE', 'OWNER ID'); ``` -------------------------------- ### Enable Implicit Grant - PHP Source: https://github.com/thephpleague/oauth2-server/wiki/Which-OAuth-2.0-grant-should-I-use? Enables the Implicit grant type for the OAuth2 server. This grant is suitable for clients that cannot securely store credentials, like JavaScript-only applications. It redirects users with an access token directly, treating the token as public knowledge with limited permissions. ```php $server->addGrantType(new League\OAuth2\Server\Grant\Implicit($server)); ``` -------------------------------- ### Retrieve Parameters from Authorization Server (PHP) Source: https://github.com/thephpleague/oauth2-server/wiki/Creating-custom-grants Shows how to retrieve parameters from the authorization server request using the getParam method. This is crucial for validating client credentials or other required inputs for a grant. ```php $authParams = $this->authServer->getParam(array('client_id', 'client_secret'), 'post', $inputParams); ``` -------------------------------- ### Add Authorization Code Grant to OAuth2 Server (PHP) Source: https://github.com/thephpleague/oauth2-server/wiki/Which-OAuth-2.0-grant-should-I-use? This snippet demonstrates how to enable the Authorization Code grant type for an OAuth2 server instance using the League OAuth2 Server library. The Authorization Code grant is commonly used for web applications where a user interacts with a client application via a browser. ```PHP $server->addGrantType(new League\OAuth2\Server\Grant\AuthCode($server)); ``` -------------------------------- ### Generate and Associate Access Token (PHP) Source: https://github.com/thephpleague/oauth2-server/wiki/Creating-custom-grants Details the steps for generating a new access token, setting its expiration time, and associating it with a previously created session. ```php // Generate an access token $accessToken = SecureKey::make(); $accessTokenExpiresIn = $this->authServer->getAccessTokenTTL(); $accessTokenExpires = time() + $accessTokenExpiresIn; $accessTokenId = $this->authServer->getStorage('session')->associateAccessToken($sessionId, $accessToken, $accessTokenExpires); ``` -------------------------------- ### Return Access Token Response (PHP) Source: https://github.com/thephpleague/oauth2-server/wiki/Creating-custom-grants Provides the final structure of the response returned after successfully completing a grant flow, including the generated access token and its details. ```php $response = array( 'access_token' => $accessToken, 'token_type' => 'bearer', 'expires' => $accessTokenExpires, 'expires_in' => $accessTokenExpiresIn ); return $response; ``` -------------------------------- ### Enable Resource Owner Password Credentials Grant - PHP Source: https://github.com/thephpleague/oauth2-server/wiki/Which-OAuth-2.0-grant-should-I-use? Enables the Resource Owner Password Credentials grant type. This allows clients to directly request a user's username and password for authentication. It's suitable for trusted clients like mobile applications or scenarios where implementing the authorization code grant is difficult. ```php $server->addGrantType(new League\OAuth2\Server\Grant\Password($server)); ``` -------------------------------- ### Enable Client Credentials Grant - PHP Source: https://github.com/thephpleague/oauth2-server/wiki/Which-OAuth-2.0-grant-should-I-use? Enables the Client Credentials grant type, which authenticates requests using only the client's credentials. This is ideal for machine-to-machine authentication, such as cron jobs or services that don't require user interaction, allowing for distinct permission sets. ```php $server->addGrantType(new League\OAuth2\Server\Grant\ClientCredentials($server)); ``` -------------------------------- ### Allow Clients Specific Scopes (PHP) Source: https://github.com/thephpleague/oauth2-server/wiki/Limit-specific-clients-to-specific-grants,-allow-specific-clients-to-use-specific-scopes-and-limit-specific-scopes-to-specific-grants Customize the `getScope()` method in the `ScopeInterface` to grant specific scopes only to authorized clients. This involves using the client ID and scope to validate access against a data source and returning `false` if unauthorized. ```PHP public function getScope($scopeId, $clientId) { // Your custom logic here to check client and scope // Example: if ($clientScope['client_id'] === $clientId && $clientScope['scope'] === $scopeId) { // return $scope; // } // return false; } ``` -------------------------------- ### Inject PDO Storage into Authorization Server Source: https://github.com/thephpleague/oauth2-server/wiki/Using-the-PDO-storage-classes This code snippet illustrates how to inject the PDO storage classes (Client, Session, Scope) into the OAuth2 Server's Authorization class. It assumes the PDO factory instance `$db` has already been created. ```php ``` -------------------------------- ### Complete Grant Flow Response Structure (PHP) Source: https://github.com/thephpleague/oauth2-server/wiki/Creating-custom-grants Defines the expected array structure for the response when completing a custom grant flow. This includes access token details, token type, and expiration information. ```php array( 'access_token' => (string), // The access token 'refresh_token' => (string), // The refresh token (only set if the refresh token grant is enabled) 'token_type' => 'bearer', // Almost always "bearer" (exceptions: JWT, SAML) 'expires' => (int), // The timestamp of when the access token will expire 'expires_in' => (int) // The number of seconds before the access token will expire ) ``` -------------------------------- ### Require State Parameter for CSRF Mitigation Source: https://github.com/thephpleague/oauth2-server/wiki/Authorization-server-customisation This method enables the requirement for the 'state' parameter in requests to help mitigate CSRF attacks. Set this to `true` to enforce its presence. ```php $server->requireStateParam(true); ``` -------------------------------- ### Limit Clients to Specific Grants (PHP) Source: https://github.com/thephpleague/oauth2-server/wiki/Limit-specific-clients-to-specific-grants,-allow-specific-clients-to-use-specific-scopes-and-limit-specific-scopes-to-specific-grants Implement custom logic in the `getClient()` method of the `ClientInterface` to restrict specific clients to particular grant types. This involves checking the client ID against a database or inline logic and returning `false` if the client is not authorized for the requested grant. ```PHP public function getClient($clientId) { // Your custom logic here to check client and grant // Example: if ($client['id'] === $clientId && $client['grant_type'] === $grantType) { // return $client; // } // return false; } ``` -------------------------------- ### Set Scope Delimiter Source: https://github.com/thephpleague/oauth2-server/wiki/Authorization-server-customisation This method allows you to change the delimiter used for scopes. While the OAuth 2.0 specification suggests a space, some providers use a comma. This method lets you specify an alternative delimiter. ```php $server->setScopeDelimeter(','); ``` -------------------------------- ### Add Custom Grant Type to OAuth2 Server (PHP) Source: https://github.com/thephpleague/oauth2-server/wiki/Creating-custom-grants Demonstrates how to add a custom grant type to the OAuth2 server instance. This involves creating a new class that implements the GrantTypeInterface and then adding it to the server. ```php $server->addGrantType(new MyGrantType($server)); ``` -------------------------------- ### Set Default Scope Source: https://github.com/thephpleague/oauth2-server/wiki/Authorization-server-customisation This method sets a default scope to be used when the 'scope' parameter is not present in the request. This default scope will be ignored if the 'scope' parameter is provided. ```php $server->setDefaultScope('user.basic'); ``` -------------------------------- ### Limit Scopes to Specific Grants (PHP) Source: https://github.com/thephpleague/oauth2-server/wiki/Limit-specific-clients-to-specific-grants,-allow-specific-clients-to-use-specific-scopes-and-limit-specific-scopes-to-specific-grants Control which scopes can be requested with specific grant types by implementing logic in the `getScope()` method of the `ScopeInterface`. This method receives the client ID and scope, allowing you to check against your database or inline rules to enforce grant-scope restrictions. ```PHP public function getScope($scopeId, $clientId, $grantType) { // Your custom logic here to check scope and grant type // Example: if ($scopeGrant['scope'] === $scopeId && $scopeGrant['grant_type'] === $grantType) { // return $scope; // } // return false; } ``` -------------------------------- ### Handle Refresh Token in Grant Response (PHP) Source: https://github.com/thephpleague/oauth2-server/wiki/Creating-custom-grants Shows how to conditionally include a refresh token in the grant response if the refresh token grant is enabled. This involves generating and associating the refresh token with the session. ```php // Associate a refresh token if set if ($this->authServer->hasGrantType('refresh_token')) { $refreshToken = SecureKey::make(); $refreshTokenTTL = time() + $this->authServer->getGrantType('refresh_token')->getRefreshTokenTTL(); $this->authServer->getStorage('session')->associateRefreshToken($accessTokenId, $refreshToken, $refreshTokenTTL); $response['refresh_token'] = $refreshToken; } return $response; ``` -------------------------------- ### Disable Scope Parameter Requirement Source: https://github.com/thephpleague/oauth2-server/wiki/Authorization-server-customisation This method allows you to disable the requirement for the 'scope' parameter in requests to the authorization server. Set this to `false` if the scope parameter is not mandatory. ```php $server->requireScopeParam(false); ``` -------------------------------- ### Set Access Token Time-to-Live (TTL) Source: https://github.com/thephpleague/oauth2-server/wiki/Authorization-server-customisation This method sets the expiration time for access tokens. By default, tokens expire after one hour (3600 seconds). You can change this value to a desired duration in seconds. It also shows how to set a specific TTL for a grant type. ```php $server->setAccessTokenTTL(86400); $server->getGrantType('client_credentials')->setAccessTokenTTL(604800); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.