Wherever you intialise your objects, initialize a new instance of the resource server with the storage interfaces:
~~~ php
$sessionStorage = new Storage\SessionStorage();
$accessTokenStorage = new Storage\AccessTokenStorage();
$clientStorage = new Storage\ClientStorage();
$scopeStorage = new Storage\ScopeStorage();
$server = new ResourceServer(
$sessionStorage,
$accessTokenStorage,
$clientStorage,
$scopeStorage
);
~~~
## Implementation
## Checking for valid access tokens
Before your API responds you need to check that an access token has been presented with the request (either in the query string `?access_token=abcdef` or as an authorization header `Authorization: Bearer abcdef`).
If you’re using a framework such as Laravel or Symfony you could use a route filter to do this. With the Slim framework you would use middleware.
This example uses Orno\Route:
~~~ php
try {
// Check that an access token is present and is valid
*`$server->getAccessToken()->getSession()->getOwnerType()` - This will return the type of the owner of the access token. For example if a user has authorized another client to use their resources the owner type would be “user”.
*`$server->getAccessToken()->getSession()->getOwnerId()` - This will return the ID of the access token owner. You can use this to check if the owner has permission to do take some sort of action (such as retrieve a document or upload a file to a folder).
*`$server->getAccessToken()->getSession()->getClient()->getId()` - Returns the ID of the client that was involved in creating the session that the access token is linked to.
*`$server->getAccessToken()` - Returns the access token used in the request.
*`$server->getAccessToken()->hasScope()` - You can use this function to see if a specific scope (or several scopes) has been associated with the access token. You can use this to limit the contents of an API response or prevent access to an API endpoint without the correct scope.
*`$server->getAccessToken()->getScopes()` - Returns all scopes attached to the access token.
This example endpoint will return a user’s information if a valid access token is present. If the access token has the `email` scope then the user's email address will be included in the response. Likewise if the `photo` scope is available the user's photo is included.
~~~ php
$router->get('/users/{username}', function (Request $request, $args) use ($server) {
$result = (new Model\Users())->get($args['username']);
if (count($result) === 0) {
throw new NotFoundException();
}
$user = [
'username' => $result[0]['username'],
'name' => $result[0]['name']
];
if ($server->hasScope('email')) {
$user['email'] = $result[0]['email'];
}
if ($server->hasScope('photo')) {
$user['photo'] = $result[0]['photo'];
}
return new Response(json_encode($user));
});
~~~
## Limiting an endpoint to a specific owner type
In this example, only a user’s access token is valid: