2014-10-01 03:14:18 +05:30
|
|
|
---
|
|
|
|
layout: default
|
|
|
|
title: Securing your API
|
|
|
|
permalink: /resource-server/securing-your-api/
|
|
|
|
---
|
|
|
|
|
|
|
|
# Securing your API
|
|
|
|
|
2016-03-24 21:15:40 +05:30
|
|
|
This library provides a PSR-7 friendly resource server middleware that can validate access tokens.
|
2014-10-01 03:14:18 +05:30
|
|
|
|
2016-03-24 21:15:40 +05:30
|
|
|
## Setup
|
2014-10-01 03:14:18 +05:30
|
|
|
|
2016-03-24 21:15:40 +05:30
|
|
|
Wherever you intialize your objects, initialize a new instance of the resource server with the storage interfaces:
|
|
|
|
|
|
|
|
{% highlight php %}
|
|
|
|
// Init our repositories
|
2016-04-17 17:46:40 +05:30
|
|
|
$accessTokenRepository = new AccessTokenRepository(); // instance of AccessTokenRepositoryInterface
|
2016-03-24 21:15:40 +05:30
|
|
|
|
2016-04-17 17:46:40 +05:30
|
|
|
// Path to authorization server's public key
|
|
|
|
$publicKey = 'file://path/to/public.key';
|
2016-03-24 21:15:40 +05:30
|
|
|
|
|
|
|
// Setup the authorization server
|
2016-04-17 17:46:40 +05:30
|
|
|
$server = new \League\OAuth2\Server\ResourceServer(
|
2016-03-24 21:15:40 +05:30
|
|
|
$accessTokenRepository,
|
|
|
|
$publicKeyPath
|
2014-10-01 03:14:18 +05:30
|
|
|
);
|
2016-03-24 21:15:40 +05:30
|
|
|
{% endhighlight %}
|
2014-10-01 03:14:18 +05:30
|
|
|
|
2016-03-24 21:15:40 +05:30
|
|
|
Then add the middleware to your stack:
|
2014-10-01 03:14:18 +05:30
|
|
|
|
2016-03-24 21:15:40 +05:30
|
|
|
{% highlight php %}
|
|
|
|
new \League\OAuth2\Server\Middleware\ResourceServerMiddleware($server);
|
|
|
|
{% endhighlight %}
|
2014-10-01 03:14:18 +05:30
|
|
|
|
2016-03-24 21:15:40 +05:30
|
|
|
## Implementation
|
2014-10-01 03:14:18 +05:30
|
|
|
|
2016-03-24 21:15:40 +05:30
|
|
|
The authorization header on an incoming request will automatically be validated.
|
2014-10-01 03:14:18 +05:30
|
|
|
|
2016-03-24 21:15:40 +05:30
|
|
|
If the access token is valid the following attributes will be set on the ServerRequest:
|
2014-10-01 03:14:18 +05:30
|
|
|
|
2016-03-24 21:15:40 +05:30
|
|
|
* `oauth_access_token_id` - the access token identifier
|
|
|
|
* `oauth_client_id` - the client identifier
|
|
|
|
* `oauth_user_id` - the user identifier represented by the access token
|
|
|
|
* `oauth_scopes` - an array of string scope identifiers
|
2014-10-01 03:14:18 +05:30
|
|
|
|
2016-03-24 21:15:40 +05:30
|
|
|
If the authorization is invalid an instance of `OAuthServerException::accessDenied` will be thrown.
|