To secure a Laravel application using Spatie packages, you generally focus on two main aspects: managing roles and permissions with spatie/laravel-permission and enhancing frontend security with spatie/laravel-csp (Content Security Policy). Below is a detailed step-by-step guide for both.
Using Spatie Laravel Permission Package to Manage Roles and Permissions
This package helps you control user access by assigning roles and permissions, protecting routes and actions.
Step 1: Install the Package
Run the following Composer command in your Laravel project root:
bash
composer require spatie/laravel-permission
Step 2: Publish Configuration and Migration Files
Publish the config and migration files with:
bash
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
Then migrate the database to create the necessary tables:
bash
php artisan migrate
Step 3: Add the HasRoles Trait to User Model
In your `app/Models/User.php`, add the trait:
php
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasRoles;
// ...
}
Step 4: Define Roles and Permissions
You can create roles and permissions programmatically, for example in a seeder or via Tinker:
php
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
// Create permissions
Permission::create(['name' => 'edit articles']);
Permission::create(['name' => 'delete articles']);
// Create roles
$adminRole = Role::create(['name' => 'admin']);
$editorRole = Role::create(['name' => 'editor']);
// Assign permissions to roles
$adminRole->givePermissionTo('edit articles');
$adminRole->givePermissionTo('delete articles');
$editorRole->givePermissionTo('edit articles');
Step 5: Assign Roles to Users
Assign roles to users in your application logic:
php
$user = User::find(1);
$user->assignRole('admin');
Step 6: Protect Routes Using Middleware
Spatie provides middleware to restrict access based on roles or permissions. Register middleware aliases if needed (usually done automatically):
php
// In routes/web.php
Route::group(['middleware' => ['role:admin']], function () {
// Routes accessible only by users with 'admin' role
});
You can also protect routes by permissions:
php
Route::group(['middleware' => ['permission:edit articles']], function () {
// Routes accessible only by users with 'edit articles' permission
});
Step 7: Use Permission Checks in Code
Within controllers or views, check permissions with:
php
if ($user->can('delete articles')) {
// Allow action
}
Using Spatie Laravel CSP Package to Add Content Security Policy
This package helps prevent XSS and other injection attacks by controlling which sources are allowed to load resources on your site.
Step 1: Install the Package
Add the package via Composer:
bash
composer require spatie/laravel-csp
Step 2: Publish Configuration (Optional)
Publish the config file if you want to customize:
bash
php artisan vendor:publish --provider="Spatie\Csp\CspServiceProvider"
Step 3: Configure CSP Policy
You can use built-in presets or define your own policy. For example, create a custom policy class:
php
namespace App\Support\Csp\Policies;
use Spatie\Csp\Policies\Basic;
use Spatie\Csp\Directive;
class CustomPolicy extends Basic
{
public function configure()
{
parent::configure();
$this->addDirective(Directive::SCRIPT, ['https://unpkg.com/vue@3/'])
->addDirective(Directive::STYLE, ['https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/'])
->addDirective(Directive::IMG, 'https://laravel.com');
}
}
Step 4: Register the Policy
In your `App\Providers\AppServiceProvider` or a dedicated service provider, register the policy:
php
use Spatie\Csp\Csp;
use App\Support\Csp\Policies\CustomPolicy;
public function boot()
{
Csp::addPolicy(CustomPolicy::class);
}
Step 5: Use Presets and Additional Directives (Laravel CSP v3+)
You can configure the package via `config/csp.php` to use presets and add directives without writing code:
php
return [
'presets' => [
Spatie\Csp\Presets\Basic::class,
Spatie\Csp\Presets\HubSpot::class,
],
'directives' => [
[Directive::SCRIPT, [Keyword::UNSAFE_INLINE, Keyword::UNSAFE_EVAL]],
// other directives...
],
];
Step 6: Test and Adjust
Test your application to ensure all necessary resources are allowed and no legitimate content is blocked. Adjust directives accordingly.
Summary
- Use spatie/laravel-permission to manage user roles and permissions, protect routes, and control access programmatically.
- Use spatie/laravel-csp to implement Content Security Policies that whitelist safe sources for scripts, styles, images, etc., reducing XSS risks.
- Both packages integrate well with Laravel and provide middleware and configuration options to secure your application effectively.
This approach covers both backend authorization and frontend resource security, significantly improving your Laravel app's overall security posture[2][3][5][8].
Citations:
[1] https://www.youtube.com/watch?v=-rheVhOCGIg
[2] https://laravel-news.com/laravel-content-security-policies
[3] https://www.youtube.com/watch?v=3hSBJCVwh78
[4] https://github.com/spatie/laravel-database-mail-templates/discussions/45
[5] https://spatie.be/blog/releasing-laravel-csp-3-and-a-call-for-contributors
[6] https://www.youtube.com/watch?v=GOeB0JFwoJQ
[7] https://www.luckymedia.dev/blog/laravel-11-for-beginners-roles-and-permissions-with-a-spatie-package
[8] https://www.linkedin.com/pulse/managing-roles-permissions-laravel-spatie-package-al-shahriar-mehedi-k9tjf
[9] https://dev.to/elvisans/managing-permissions-in-laravel-applications-using-spatie-1le
[10] https://www.allphptricks.com/laravel-11-spatie-user-roles-and-permissions/