Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions config/graphql.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@
'users' => false,
],

/*
|--------------------------------------------------------------------------
| Authentication
|--------------------------------------------------------------------------
|
| By default, the GraphQL API will be publicly accessible. However, you
| may define an API token here which will be used to authenticate requests.
|
*/

'auth_token' => env('STATAMIC_GRAPHQL_AUTH_TOKEN'),

/*
|--------------------------------------------------------------------------
| Queries
Expand Down
5 changes: 5 additions & 0 deletions resources/views/graphql/graphiql.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@

const fetcher = createGraphiQLFetcher({
url: '{{ $url }}',
@if ($authToken)
headers: {
'Authorization': 'Bearer {{ $authToken }}',
},
@endif
});

let plugins = [HISTORY_PLUGIN];
Expand Down
3 changes: 2 additions & 1 deletion src/GraphQL/DefaultSchema.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Rebing\GraphQL\Support\Contracts\ConfigConvertible;
use Statamic\Facades\GraphQL;
use Statamic\GraphQL\Middleware\CacheResponse;
use Statamic\GraphQL\Middleware\HandleAuthentication;
use Statamic\GraphQL\Queries\AssetContainerQuery;
use Statamic\GraphQL\Queries\AssetContainersQuery;
use Statamic\GraphQL\Queries\AssetQuery;
Expand Down Expand Up @@ -77,7 +78,7 @@ private function getQueries()
private function getMiddleware()
{
return array_merge(
[CacheResponse::class],
[HandleAuthentication::class, CacheResponse::class],
config('statamic.graphql.middleware', []),
GraphQL::getExtraMiddleware()
);
Expand Down
26 changes: 26 additions & 0 deletions src/GraphQL/Middleware/HandleAuthentication.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace Statamic\GraphQL\Middleware;

use Closure;

class HandleAuthentication
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
public function handle($request, Closure $next)
{
if (
($token = config('statamic.graphql.auth_token'))
&& ($request->bearerToken() !== $token)
) {
abort(401);
}

return $next($request);
}
}
1 change: 1 addition & 0 deletions src/Http/Controllers/CP/GraphQLController.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public function graphiql()
return view('statamic::graphql.graphiql', [
'url' => '/'.config('graphql.route.prefix'),
'introspection' => GraphQL::introspectionEnabled(),
'authToken' => config('statamic.graphql.auth_token'),
]);
}
}
91 changes: 91 additions & 0 deletions tests/Feature/GraphQL/AuthenticationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?php

namespace Tests\Feature\GraphQL;

use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\Test;
use Statamic\Facades\Config;
use Tests\PreventSavingStacheItemsToDisk;
use Tests\TestCase;

#[Group('graphql')]
class AuthenticationTest extends TestCase
{
use PreventSavingStacheItemsToDisk;

#[Test]
public function it_can_authenticate_using_auth_token()
{
Config::set('statamic.graphql.auth_token', 'foobar');

$this
->withToken('foobar')
->postJson('/graphql', ['query' => '{ping}'])
->assertOk();
}

#[Test]
public function it_cant_authenticate_with_invalid_auth_token()
{
Config::set('statamic.graphql.auth_token', 'foobar');

$this
->withToken($token = 'invalid')
->postJson($url = '/graphql', ['query' => '{ping}'])
->assertUnauthorized();

$this
->withToken($token)
->post($url, ['query' => '{ping}'])
->assertUnauthorized();
}

#[Test]
public function it_cant_authenticate_without_auth_token()
{
Config::set('statamic.graphql.auth_token', 'foobar');

$this
->postJson($url = '/graphql', ['query' => '{ping}'])
->assertUnauthorized();

$this
->post($url, ['query' => '{ping}'])
->assertUnauthorized();
}

#[Test]
public function authentication_only_required_when_auth_token_is_set()
{
Config::set('statamic.graphql.auth_token', null);

$this
->postJson($url = '/graphql', ['query' => '{ping}'])
->assertOk();

$this
->post($url, ['query' => '{ping}'])
->assertOk();
}

#[Test]
public function authenticated_responses_are_not_served_to_unauthenticated_requests()
{
Config::set('statamic.graphql.auth_token', 'foobar');
Config::set('statamic.graphql.cache', ['expiry' => 60]);

// First, make an authenticated request that gets cached
$this
->withToken('foobar')
->postJson('/graphql', ['query' => '{ping}'])
->assertOk()
->assertJsonPath('data.ping', 'pong');

// Now make an unauthenticated request - should get 401, not cached response
// This verifies auth happens before caching
$this
->withoutToken()
->postJson('/graphql', ['query' => '{ping}'])
->assertUnauthorized();
}
}
Loading