Skip to content

Commit 8f5e164

Browse files
authored
Merge pull request #11 from TomHAnderson/feature/request-attribute
Authorized ApiKey is assigned to request attribute 'apikey'
2 parents b2abd2c + d8b7f79 commit 8f5e164

File tree

4 files changed

+14
-0
lines changed

4 files changed

+14
-0
lines changed

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,16 @@ Route::name('api.resource::fetch')
8888
```
8989

9090

91+
## Access to ApiKey through request attributes
92+
93+
The ApiKey entity which authenticates a request is assigned to the request attributes as
94+
'apikey'.
95+
96+
```php
97+
$apiKey = request()->attributes->get('apikey');
98+
```
99+
100+
91101
## Leveraging the ApiKey name as a foreign key
92102

93103
It stands to reason that in many cases one API key will be issued for exactly one user.

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
"require-dev": {
2727
"doctrine/coding-standard": "^9.0",
2828
"doctrine/dbal": "^3.1.1",
29+
"doctrine/annotations": "^1.13.2",
2930
"orchestra/testbench": "^6.23",
3031
"phpunit/phpunit": "^9.5",
3132
"vimeo/psalm": "^4.15"

src/Http/Middleware/AuthorizeApiKey.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,15 @@ public function handle(Request $request, Closure $next, ?string $scope = null):
4141
if ($apiKey) {
4242
if (! $scope) {
4343
$this->apiKeyService->logAccessEvent($request, $apiKey);
44+
$request->attributes->set('apikey', $apiKey);
4445

4546
return $next($request);
4647
}
4748

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

5254
return $next($request);
5355
}

test/Feature/Http/Middleware/AuthorizeApiKeyTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ public function testApiKeyAuthorizesRequest(): void
2626

2727
$response = $middleware->handle($request, function() {});
2828
$this->assertNull($response);
29+
$this->assertEquals($apiKey, $request->attributes->get('apikey'));
2930
}
3031

3132
public function testApiKeyDoesNotAuthorizeRequest(): void

0 commit comments

Comments
 (0)