diff --git a/composer.json b/composer.json index 77dbef606..ef9aa3942 100644 --- a/composer.json +++ b/composer.json @@ -20,7 +20,6 @@ "league/fractal": "^0.19" }, "require-dev": { - "phpdocumentor/reflection-docblock": "3.3.2", "friendsofphp/php-cs-fixer": "~2", "illuminate/auth": "^7.0|^8.0", "illuminate/cache": "^7.0|^8.0", @@ -32,6 +31,7 @@ "illuminate/pagination": "^7.0|^8.0", "laravel/lumen-framework": "^7.0|^8.0", "mockery/mockery": "~1.0", + "phpdocumentor/reflection-docblock": "3.3.2", "phpunit/phpunit": "^8.5|^9.0", "squizlabs/php_codesniffer": "~2.0", "tymon/jwt-auth": "1.0.*" diff --git a/config/api.php b/config/api.php index d6e883600..5a1931c36 100644 --- a/config/api.php +++ b/config/api.php @@ -154,7 +154,8 @@ */ 'middleware' => [ - + // If you are using sanctum spa authentication, please turn off the Comment. + // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class ], /* diff --git a/src/Auth/Provider/SanctumSPA.php b/src/Auth/Provider/SanctumSPA.php new file mode 100644 index 000000000..fee15ff6d --- /dev/null +++ b/src/Auth/Provider/SanctumSPA.php @@ -0,0 +1,49 @@ +auth = $auth; + } + + /** + * Authenticate request with Basic. + * + * @param \Illuminate\Http\Request $request + * @param \Dingo\Api\Routing\Route $route + * + * @return mixed + */ + public function authenticate(Request $request, Route $route) + { + if ($user = $this->auth->guard('web')->user()) { + return $user; + } + throw new UnauthorizedHttpException('', + 'Unauthenticated' + ); + } +} diff --git a/tests/Auth/Provider/SanctumSPATest.php b/tests/Auth/Provider/SanctumSPATest.php new file mode 100644 index 000000000..cc302c32b --- /dev/null +++ b/tests/Auth/Provider/SanctumSPATest.php @@ -0,0 +1,48 @@ +auth = m::mock('Illuminate\Auth\AuthManager'); + $this->provider = new SanctumSPA($this->auth); + } + + public function testInvalidSanctumCredentialsThrowsException() + { + $this->expectException(UnauthorizedHttpException::class); + + $request = Request::create('GET', '/'); + + $this->auth->shouldReceive('guard')->andReturn(m::self()); + + $this->auth->shouldReceive('user')->once()->andReturn(null); + + $this->provider->authenticate($request, m::mock(Route::class)); + } + + public function testAuthenticatingSucceedsAndReturnsUserObject() + { + $request = Request::create('GET', '/'); + + $this->auth->shouldReceive('guard')->andReturn(m::self()); + + $this->auth->shouldReceive('user')->once()->andReturn((object) ['id' => 1]); + + $this->assertSame(1, $this->provider->authenticate($request, m::mock(Route::class))->id); + } +}