This package is an authentication backend implementation for Laravel. Registers the routes and controllers required to implement all Laravel authentication features from a Frontend SPA or SSR, including login, password reset, and more.
composer require descom/laravel-auth-spa
Run:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
Add Sanctum's middleware to your api middleware group within your application's app/Http/Kernel.php
file:
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Configure cors, you need edit the file config/cors.php
and change this lines:
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout', 'password/forget', 'password/reset'],
/// ...
'supports_credentials' => true,
In production define this environment variables:
Local:
SANCTUM_STATEFUL_DOMAINS=localhost:3000
SESSION_DOMAIN=localhost
Production for domain 'www.app.tld':
SANCTUM_STATEFUL_DOMAINS=www.app.tld
SESSION_DOMAIN=.app.tld
php artisan vendor:publish --provider="Descom\AuthSpa\AuthSpaServiceProvider" --tag="config"
You can define your frontend in config file config/authspa.php
///
'frontend' => [
'url' => env('FRONTEND_URL', 'http://localhost:3000'),
'reset_password_url' => env('FRONTEND_RESET_PASSWORD_URL', '/login/reset'),
],
///
- [POST]
/login
- [POST]
/logout
- [POST]
/password/reset_link
- [POST]
/password/reset
- [GET]
/api/user
Install Nuxt Auth:
yarn add --exact @nuxtjs/auth-next
yarn add @nuxtjs/axios
And configure file nuxt.config.js
:
{
modules: [
'@nuxtjs/axios',
'@nuxtjs/auth-next'
],
auth: {
strategies: {
laravelSanctum: {
provider: 'laravel/sanctum',
url: process.env.API_URL || 'http://localhost:8000',
},
},
}
}
You can define your own controller to get User Info, edit the file config/auth-spa.php
'http' => [
'profile_info' => [
'controller' => \Descom\AuthSpa\Http\Controllers\ProfileInfoController::class,
'middleware' => ['api', 'auth:sanctum'],
'path' => 'user',
],
],
And define your own controller:
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
class UserInfoController extends Controller
{
public function __invoke(): JsonResponse
{
return response()->json(Auth::user()->load(['roles', 'clients']));
}
}