Docs Menu
Docs Home
/ / /
Laravel MongoDB

User Authentication

On this page

  • Overview
  • Modify the User Model
  • Example
  • Create the User Controller
  • Example
  • Customize User Authentication
  • Laravel Sanctum
  • Laravel Passport
  • Password Reminders
  • Additional Information

In this guide, you can learn how to authenticate MongoDB users by using Laravel's native authentication functionality.

Laravel provides a native Auth module that includes authentication services, such as guards that define how users are authenticated and providers that define how users are retrieved. To learn more about these services, see Authentication in the Laravel documentation.

By default, Laravel generates the User Eloquent model in your App/Models directory. To enable authentication for MongoDB users, your User model must extend the MongoDB\Laravel\Auth\User class.

To extend this class, navigate to your app/Models/User.php file and replace the use Illuminate\Foundation\Auth\User as Authenticatable statement with the following code:

use MongoDB\Laravel\Auth\User as Authenticatable;

Next, ensure that your User class extends Authenticatable, as shown in the following code:

class User extends Authenticatable
{
...
}

After configuring your User model, create a corresponding controller. To learn how to create a controller, see the Create the User Controller section on this page.

The following code shows a User.php file that extends the MongoDB\Laravel\Auth\User class:

<?php
namespace App\Models;
use MongoDB\Laravel\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $connection = 'mongodb';
protected $table = 'users';
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
}

To store functions that manage authentication, create an authentication controller for your User model.

Run the following command from your project root to create a controller:

php artisan make:controller <filename>

The following command creates a controller file called AuthController.php:

php artisan make:controller AuthController

The AuthController.php file can store login() and logout() functions to manage user authentication, as shown in the following code:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use function response;
class AuthController extends Controller
{
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
if (Auth::attempt($request->only('email', 'password'))) {
return response()->json([
'user' => Auth::user(),
'message' => 'Successfully logged in',
]);
}
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
public function logout()
{
Auth::logout();
return response()->json(['message' => 'Successfully logged out']);
}
}

You can customize your authentication files to align with your application's needs and enable additional authentication features.

This section describes how to use the following features to customize the MongoDB user authentication process:

Laravel Sanctum is an authentication package that can manage API requests and single-page application authentication. To manage API requests, Sanctum issues API tokens that are stored in the database and authenticates incoming HTTP requests by using the Authorization header. To authenticate single-page applications, Sanctum uses Laravel's cookie-based authentication services.

You can install Laravel Sanctum to manage your application's authentication process. Run the following commands from your project root to install Laravel Sanctum and publish its migration file:

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

To use Laravel Sanctum with the Laravel Integration, modify the PersonalAccessToken model provided by Sanctum to use the DocumentModel trait from the MongoDB\Laravel\Eloquent namespace. The following code modifies the PersonalAccessToken model to enable MongoDB:

<?php
namespace App\Models;
use Laravel\Sanctum\PersonalAccessToken as SanctumToken;
use MongoDB\Laravel\Eloquent\DocumentModel;
class PersonalAccessToken extends SanctumToken
{
use DocumentModel;
protected $connection = 'mongodb';
protected $table = 'personal_access_tokens';
protected $keyType = 'string';
}

Next, run the following command to modify the database schema:

php artisan migrate

You can now instruct Sanctum to use the custom PersonalAccessToken model by calling the usePersonalAccessTokenModel() method in one of your application's service providers. To learn more, see Overriding Default Models in the Laravel Sanctum guide.

Tip

To learn more about the DocumentModel trait, see Extend Third-Party Model Classes in the Eloquent Model Class guide.

Laravel Passport is an OAuth 2.0 server implementation that offers API authentication for Laravel applications. Use Laravel Passport if your application requires OAuth2 support.

Tip

To learn more about Laravel Passport and the OAuth 2.0 protocol, see the following resources:

To install Laravel Passport and run the database migrations required to store OAuth2 clients, run the following command from your project root:

php artisan install:api --passport

Next, navigate to your User model and add the Laravel\Passport\HasApiTokens trait. This trait provides helper methods that allow you to inspect a user's authentication token and scopes. The following code shows how to add Laravel\Passport\HasApiTokens to your app\Models\User.php file:

<?php
namespace App\Models;
use MongoDB\Laravel\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
...
}

Then, define an api authentication guard in your config\auth.php file and set the driver option to passport. This instructs your application to use Laravel Passport's TokenGuard class to authenticate API requests. The following example adds the api authentication guard to the guards array:

'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],

After installing Laravel Passport, you must enable Passport compatibility with MongoDB by defining custom Laravel Integration models that extend the corresponding Passport models. To extend each Passport model class, include the DocumentModel trait in the custom models. You can define the following Laravel Integration model classes:

  • MongoDB\Laravel\Passport\AuthCode, which extends Laravel\Passport\AuthCode

  • MongoDB\Laravel\Passport\Client, which extends Laravel\Passport\Client

  • MongoDB\Laravel\Passport\PersonalAccessClient, which extends Laravel\Passport\PersonalAccessClient

  • MongoDB\Laravel\Passport\RefreshToken, which extends Laravel\Passport\RefreshToken

  • MongoDB\Laravel\Passport\Token, which extends Laravel\Passport\Token

The following example code extends the default Laravel\Passport\AuthCode model class when defining a MongoDB\Laravel\Passport\AuthCode class and includes the DocumentModel trait:

class MongoDB\Laravel\Passport\AuthCode extends Laravel\Passport\AuthCode
{
use MongoDB\Laravel\Eloquent\DocumentModel;
protected $primaryKey = '_id';
protected $keyType = 'string';
}

After defining custom models that extend each Laravel\Passport class, instruct Passport to use the models in the boot() method of your application's App\Providers\AppServiceProvider class. The following example adds each custom model to the boot() method:

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use MongoDB\Laravel\Passport\AuthCode;
use MongoDB\Laravel\Passport\Client;
use MongoDB\Laravel\Passport\PersonalAccessClient;
use MongoDB\Laravel\Passport\RefreshToken;
use MongoDB\Laravel\Passport\Token;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Passport::useAuthCodeModel(AuthCode::class);
Passport::useClientModel(Client::class);
Passport::usePersonalAccessClientModel(PersonalAccessClient::class);
Passport::useRefreshTokenModel(RefreshToken::class);
Passport::useTokenModel(Token::class);
}
}

Then, you can use Laravel Passport and MongoDB in your application.

To add support for MongoDB-based password reminders, register the following service provider in your application:

MongoDB\Laravel\Auth\PasswordResetServiceProvider::class

This service provider modifies the internal DatabaseReminderRepository to enable password reminders.

The following code updates the providers.php file in the bootstrap directory of a Laravel application to register the PasswordResetServiceProvider provider:

return [
App\Providers\AppServiceProvider::class,
MongoDB\Laravel\MongoDBServiceProvider::class,
MongoDB\Laravel\Auth\PasswordResetServiceProvider::class
];

To learn more about user authentication, see Authentication in the Laravel documentation.

To learn more about Eloquent models, see the Eloquent Model Class guide.

Back

Query Builder