oauth2-server/auth-server-client-credentials.md

68 lines
2.4 KiB
Markdown
Raw Normal View History

2014-10-01 03:14:18 +05:30
---
layout: default
title: Authorization server with client credentials grant
permalink: /authorization-server/client-credentials-grant/
---
2016-03-16 02:03:44 +05:30
# Client credentials grant
This grant is similar to the resource owner credentials grant except only the clients credentials are used to authenticate a request for an access token. Again this grant should only be allowed to be used by trusted clients.
This grant is suitable for machine-to-machine authentication, for example for use in a cron job which is performing maintenance tasks over an API. Another example would be a client making requests to an API that dont require users permission.
2014-10-01 03:14:18 +05:30
## Setup
2016-03-16 02:03:44 +05:30
Wherever you initialize your objects, initialize a new instance of the authorization server and bind the storage interfaces and authorization code grant:
{% highlight php %}
// Your implementation of the required repositories
$clientRepository = new ClientRepository();
$accessTokenRepository = new AccessTokenRepository();
$scopeRepository = new ScopeRepository();
2014-10-01 03:14:18 +05:30
2016-03-16 02:03:44 +05:30
$privateKeyPath = 'file://path/to/private.key';
$publicKeyPath = 'file://path/to/public.key';
2014-10-01 03:14:18 +05:30
2016-03-16 02:03:44 +05:30
// Setup the authorization server
$server = new Server(
$clientRepository,
$accessTokenRepository,
$scopeRepository,
$privateKeyPath,
$publicKeyPath
);
2014-10-01 03:14:18 +05:30
2016-03-16 02:03:44 +05:30
// Enable the client credentials grant on the server with a token TTL of 1 hour
$server->enableGrantType(
new ClientCredentialsGrant(),
new \DateInterval('PT1H')
);
{% endhighlight %}
2014-10-01 03:14:18 +05:30
## Implementation
The client will request an access token so create an `/access_token` endpoint.
2016-03-16 02:03:44 +05:30
{% highlight php %}
$app->post('/access_token', function (ServerRequestInterface $request, ResponseInterface $response) use ($app) {
2014-10-01 03:14:18 +05:30
2016-03-16 02:03:44 +05:30
// Retrieve the authorization server from the DI container
$server = $app->getContainer()->get(Server::class);
2014-10-01 03:14:18 +05:30
try {
2016-03-16 02:03:44 +05:30
// A successful response with an access token
return $server->respondToRequest($request, $response);
} catch (OAuthServerException $exception) {
// A correctly formatted OAuth error response
return $exception->generateHttpResponse($response);
} catch (\Exception $exception) {
// An unknown server error
$body = new Stream('php://temp', 'r+');
$body->write($exception->getMessage());
return $response->withStatus(500)->withBody($body);
2014-10-01 03:14:18 +05:30
}
});
2016-03-16 02:03:44 +05:30
{% endhighlight %}