PHPackages                             nahidferdous/laravel-shield - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. nahidferdous/laravel-shield

ActiveLibrary[API Development](/categories/api)

nahidferdous/laravel-shield
===========================

Shield - A comprehensive Laravel package for authentication (Sanctum, Passport, JWT), socialite and role/permission management with social login support.

1.0.8(4mo ago)37MITPHPPHP ^8.2

Since Dec 15Pushed 4mo agoCompare

[ Source](https://github.com/nahidnfr123/laravel-shield)[ Packagist](https://packagist.org/packages/nahidferdous/laravel-shield)[ Docs](https://github.com/nahidnfr123/laravel-shield)[ RSS](/packages/nahidferdous-laravel-shield/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (10)Versions (9)Used By (0)

[![logo.png](logo.png)](logo.png)

Laravel Shield - Complete Authentication Package
================================================

[](#laravel-shield---complete-authentication-package)

A comprehensive Laravel package for authentication (Sanctum, Passport, JWT) and role/permission management with social login support.

Features
--------

[](#features)

- 🔐 Multiple authentication drivers (Sanctum, Passport, JWT)
- 👥 Social login (Google, Facebook, GitHub, Twitter, LinkedIn)
- 🛡️ Role-based access control (RBAC)
- 🔑 Permission/Privilege management
- 💾 Caching support
- 🚀 Production-ready out of the box
- 📝 Comprehensive CLI commands

Installation
------------

[](#installation)

```
composer require nahidferdous/shield
```

Quick Start
-----------

[](#quick-start)

### 1. Install Shield

[](#1-install-shield)

```
php artisan shield:install
```

This will:

- Publish configuration file
- Run migrations
- Prepare your User model
- Seed default roles

### 2. Choose Authentication Driver

[](#2-choose-authentication-driver)

Edit `.env`:

```
SHIELD_AUTH_DRIVER=sanctum  # Options: sanctum, passport, jwt
```

### 3. Configure Authentication Driver

[](#3-configure-authentication-driver)

#### For Sanctum (Default)

[](#for-sanctum-default)

```
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
```

#### For Passport

[](#for-passport)

```
php artisan passport:install
composer require laravel/passport
```

Add to `.env`:

```
PASSPORT_PERSONAL_ACCESS_CLIENT_ID=your-client-id
PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET=your-client-secret
```

#### For JWT

[](#for-jwt)

```
composer require firebase/php-jwt
```

Add to `.env`:

```
JWT_SECRET=your-secret-key
JWT_TTL=60
JWT_REFRESH_TTL=20160
```

### 4. Enable Social Login (Optional)

[](#4-enable-social-login-optional)

```
composer require laravel/socialite socialiteproviders/manager
```

Edit `.env`:

```
SHIELD_SOCIAL_LOGIN_ENABLED=true

# Google
GOOGLE_LOGIN_ENABLED=true
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
GOOGLE_REDIRECT_URL="${APP_URL}/api/auth/google/callback"

# Facebook
FACEBOOK_LOGIN_ENABLED=true
FACEBOOK_CLIENT_ID=your-app-id
FACEBOOK_CLIENT_SECRET=your-app-secret

# GitHub
GITHUB_LOGIN_ENABLED=true
GITHUB_CLIENT_ID=your-client-id
GITHUB_CLIENT_SECRET=your-client-secret
```

API Endpoints
-------------

[](#api-endpoints)

### Authentication

[](#authentication)

#### Register

[](#register)

```
POST /api/register
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "password123"
}
```

#### Login

[](#login)

```
POST /api/login
Content-Type: application/json

{
  "email": "john@example.com",
  "password": "password123"
}
```

Response:

```
{
  "error": 0,
  "id": 1,
  "name": "John Doe",
  "email": "john@example.com",
  "token": "your-access-token",
  "token_type": "Bearer"
}
```

#### Logout

[](#logout)

```
POST /api/logout
Authorization: Bearer your-access-token
```

#### Refresh Token

[](#refresh-token)

```
POST /api/refresh
Authorization: Bearer your-access-token
```

#### Get Current User

[](#get-current-user)

```
GET /api/me
Authorization: Bearer your-access-token
```

### Social Authentication

[](#social-authentication)

#### Get Enabled Providers

[](#get-enabled-providers)

```
GET /api/auth/providers
```

Response:

```
{
  "error": 0,
  "providers": ["google", "facebook", "github"]
}
```

#### Redirect to Provider

[](#redirect-to-provider)

```
GET /api/auth/{provider}/redirect
```

Example: `GET /api/auth/google/redirect`

#### Handle Callback

[](#handle-callback)

```
GET /api/auth/{provider}/callback
```

This endpoint is called automatically by the OAuth provider.

### User Management

[](#user-management)

#### List Users

[](#list-users)

```
GET /api/users
Authorization: Bearer your-access-token
```

#### Get User

[](#get-user)

```
GET /api/users/{id}
Authorization: Bearer your-access-token
```

#### Update User

[](#update-user)

```
PUT /api/users/{id}
Authorization: Bearer your-access-token
Content-Type: application/json

{
  "name": "Updated Name",
  "email": "updated@example.com"
}
```

#### Delete User

[](#delete-user)

```
DELETE /api/users/{id}
Authorization: Bearer your-access-token
```

### Role Management

[](#role-management)

#### List Roles

[](#list-roles)

```
GET /api/roles
Authorization: Bearer your-access-token
```

#### Create Role

[](#create-role)

```
POST /api/roles
Authorization: Bearer your-access-token
Content-Type: application/json

{
  "name": "Editor",
  "slug": "editor",
  "description": "Can edit content"
}
```

#### Assign Role to User

[](#assign-role-to-user)

```
POST /api/roles/{roleId}/users/{userId}
Authorization: Bearer your-access-token
```

#### Remove Role from User

[](#remove-role-from-user)

```
DELETE /api/roles/{roleId}/users/{userId}
Authorization: Bearer your-access-token
```

### Privilege Management

[](#privilege-management)

#### List Privileges

[](#list-privileges)

```
GET /api/privileges
Authorization: Bearer your-access-token
```

#### Create Privilege

[](#create-privilege)

```
POST /api/privileges
Authorization: Bearer your-access-token
Content-Type: application/json

{
  "name": "Edit Posts",
  "slug": "edit-posts",
  "description": "Can edit blog posts"
}
```

#### Attach Privilege to Role

[](#attach-privilege-to-role)

```
POST /api/privileges/{privilegeId}/roles/{roleId}
Authorization: Bearer your-access-token
```

CLI Commands
------------

[](#cli-commands)

### User Management

[](#user-management-1)

```
php artisan shield:create-user           # Create a new user
php artisan shield:list-users            # List all users
php artisan shield:update-user           # Update user details
php artisan shield:delete-user           # Delete a user
php artisan shield:suspend-user          # Suspend a user
php artisan shield:unsuspend-user        # Unsuspend a user
php artisan shield:login                 # Login via CLI
php artisan shield:logout                # Logout current session
```

### Role Management

[](#role-management-1)

```
php artisan shield:add-role              # Create a new role
php artisan shield:list-roles            # List all roles
php artisan shield:update-role           # Update role details
php artisan shield:delete-role           # Delete a role
php artisan shield:assign-role           # Assign role to user
php artisan shield:delete-user-role      # Remove role from user
```

### Privilege Management

[](#privilege-management-1)

```
php artisan shield:add-privilege         # Create a privilege
php artisan shield:list-privileges       # List all privileges
php artisan shield:update-privilege      # Update privilege
php artisan shield:delete-privilege      # Delete privilege
php artisan shield:attach-privilege      # Attach privilege to role
php artisan shield:detach-privilege      # Detach privilege from role
```

Middleware
----------

[](#middleware)

### Role-Based Middleware

[](#role-based-middleware)

```
// Single role
Route::middleware(['auth:sanctum', 'role:admin'])->group(function () {
    // Admin only routes
});

// Multiple roles (any)
Route::middleware(['auth:sanctum', 'roles:admin,moderator'])->group(function () {
    // Admin or Moderator routes
});
```

### Privilege-Based Middleware

[](#privilege-based-middleware)

```
// Single privilege
Route::middleware(['auth:sanctum', 'privilege:edit-posts'])->group(function () {
    // Routes for users with edit-posts privilege
});

// Multiple privileges (any)
Route::middleware(['auth:sanctum', 'privileges:edit-posts,delete-posts'])->group(function () {
    // Routes for users with any of these privileges
});
```

Configuration
-------------

[](#configuration)

Publish and edit `config/shield.php`:

```
return [
    // Authentication driver
    'auth_driver' => env('SHIELD_AUTH_DRIVER', 'sanctum'),

    // Default user role
    'default_user_role_slug' => env('DEFAULT_ROLE_SLUG', 'user'),

    // Delete previous tokens on login
    'delete_previous_access_tokens_on_login' => env('DELETE_PREVIOUS_ACCESS_TOKENS_ON_LOGIN', false),

    // Social login
    'social' => [
        'enabled' => env('SHIELD_SOCIAL_LOGIN_ENABLED', false),
        'auto_create_user' => true,
        'auto_verify_email' => true,
    ],

    // JWT configuration
    'jwt' => [
        'secret' => env('JWT_SECRET'),
        'ttl' => env('JWT_TTL', 60),
        'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),
    ],

    // Cache
    'cache' => [
        'enabled' => env('SHIELD_CACHE_ENABLED', true),
        'ttl' => env('SHIELD_CACHE_TTL', 300),
    ],
];
```

Switching Between Authentication Drivers
----------------------------------------

[](#switching-between-authentication-drivers)

Simply change the `SHIELD_AUTH_DRIVER` in your `.env`:

```
# Use Sanctum
SHIELD_AUTH_DRIVER=sanctum

# Use Passport
SHIELD_AUTH_DRIVER=passport

# Use JWT
SHIELD_AUTH_DRIVER=jwt
```

No code changes required! Shield handles the rest automatically.

User Model Setup
----------------

[](#user-model-setup)

Your User model should use the Shield traits:

```
use NahidFerdous\Shield\Traits\HasRoles;
use Laravel\Sanctum\HasApiTokens;  // or Laravel\Passport\HasApiTokens for Passport

class User extends Authenticatable
{
    use HasApiTokens, HasRoles;

    protected $fillable = [
        'name',
        'email',
        'password',
        'provider',
        'provider_id',
        'avatar',
    ];
}
```

Testing Social Login Locally
----------------------------

[](#testing-social-login-locally)

Use ngrok or similar tool to expose your local server:

```
ngrok http 8000
```

Then update your OAuth app redirect URLs to use the ngrok URL.

Security
--------

[](#security)

- Always use HTTPS in production
- Keep your JWT secret secure
- Rotate tokens regularly
- Enable token blacklisting for JWT
- Implement rate limiting on login endpoints

License
-------

[](#license)

MIT License

Support
-------

[](#support)

For issues and questions, please open an issue on GitHub.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance74

Regular maintenance activity

Popularity8

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 54.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

7

Last Release

148d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/3b39f70d3f5933f45d33670bd426842203b6d538809169ed4d9891a680288b68?d=identicon)[nahidnfr123](/maintainers/nahidnfr123)

---

Top Contributors

[![encoderit-nahid](https://avatars.githubusercontent.com/u/163091309?v=4)](https://github.com/encoderit-nahid "encoderit-nahid (12 commits)")[![nahidnfr123](https://avatars.githubusercontent.com/u/65497148?v=4)](https://github.com/nahidnfr123 "nahidnfr123 (10 commits)")

---

Tags

apilaravelsocialitepassportsanctumroles

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/nahidferdous-laravel-shield/health.svg)

```
[![Health](https://phpackages.com/badges/nahidferdous-laravel-shield/health.svg)](https://phpackages.com/packages/nahidferdous-laravel-shield)
```

###  Alternatives

[darkaonline/l5-swagger

OpenApi or Swagger integration to Laravel

2.9k34.0M112](/packages/darkaonline-l5-swagger)[knuckleswtf/scribe

Generate API documentation for humans from your Laravel codebase.✍

2.3k12.2M45](/packages/knuckleswtf-scribe)[mollie/laravel-mollie

Mollie API client wrapper for Laravel &amp; Mollie Connect provider for Laravel Socialite

3624.1M28](/packages/mollie-laravel-mollie)[hasinhayder/tyro

Tyro - The ultimate Authentication, Authorization, and Role &amp; Privilege Management solution for Laravel 12 &amp; 13

6712.1k2](/packages/hasinhayder-tyro)[rupadana/filament-api-service

A simple api service for supporting filamentphp

204103.8k7](/packages/rupadana-filament-api-service)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
