Skip to content

Commit

Permalink
Merge pull request #11 from TomHAnderson/feature/request-attribute
Browse files Browse the repository at this point in the history
Authorized ApiKey is assigned to request attribute 'apikey'
  • Loading branch information
TomHAnderson authored Jan 13, 2022
2 parents b2abd2c + d8b7f79 commit 8f5e164
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,16 @@ Route::name('api.resource::fetch')
```


## Access to ApiKey through request attributes

The ApiKey entity which authenticates a request is assigned to the request attributes as
'apikey'.

```php
$apiKey = request()->attributes->get('apikey');
```


## Leveraging the ApiKey name as a foreign key

It stands to reason that in many cases one API key will be issued for exactly one user.
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"require-dev": {
"doctrine/coding-standard": "^9.0",
"doctrine/dbal": "^3.1.1",
"doctrine/annotations": "^1.13.2",
"orchestra/testbench": "^6.23",
"phpunit/phpunit": "^9.5",
"vimeo/psalm": "^4.15"
Expand Down
2 changes: 2 additions & 0 deletions src/Http/Middleware/AuthorizeApiKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,15 @@ public function handle(Request $request, Closure $next, ?string $scope = null):
if ($apiKey) {
if (! $scope) {
$this->apiKeyService->logAccessEvent($request, $apiKey);
$request->attributes->set('apikey', $apiKey);

return $next($request);
}

// If a scope is passed then verify it exists for the key
if ($this->apiKeyService->hasScope($key, $scope)) {
$this->apiKeyService->logAccessEvent($request, $apiKey);
$request->attributes->set('apikey', $apiKey);

return $next($request);
}
Expand Down
1 change: 1 addition & 0 deletions test/Feature/Http/Middleware/AuthorizeApiKeyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public function testApiKeyAuthorizesRequest(): void

$response = $middleware->handle($request, function() {});
$this->assertNull($response);
$this->assertEquals($apiKey, $request->attributes->get('apikey'));
}

public function testApiKeyDoesNotAuthorizeRequest(): void
Expand Down

0 comments on commit 8f5e164

Please sign in to comment.