In a Laravel 10 application, there are various API authentication systems available, such as Laravel Passport, Laravel Sanctum, and JWT authentication. This tutorial will guide you through creating API authentication in Laravel 10 using JSON Web Tokens (JWT).
For this tutorial, we will use the php-open-source-saver/jwt-auth ** package, which is a fork of **tymondesigns/jwt-auth . The original package is not compatible with Laravel 9 and Laravel 10, making the forked version necessary for our purposes.
JWT API authentication is more secure compared to Laravel Sanctum or Laravel Passport. In this tutorial, you will learn how to create a complete JWT-authenticated Laravel 10 application. We will cover the creation of Login, Register, Logout, and Refresh Token APIs, all implemented with POST requests. Let’s begin our Laravel 10 JWT authentication tutorial:
STEP 1: INSTALL LARAVEL PROJECT
First of all, we need to get a fresh Laravel 10 version application using the bellow command to start tymonjwt auth laravel 10.
composer create-project laravel/laravel Auth
STEP 2: CONNECT YOUR DATABASE
I am going to use the MYSQL database for this jwt auth laravel 10. So connect the database by updating.env like this:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=YOUR_DB_NAME
DB_USERNAME=YOUR_DB_USERNAME
DB_PASSWORD=YOUR_DB_PASSWORD
Now run php artisan migrate command to migrate the database.
STEP 3: INSTALL JSON WEB TOKEN(JWT)
In this step, we will install php-open-source-saver/jwt-auth package. So open the terminal and run the below command:
composer require php-open-source-saver/jwt-auth
And now publish the configuration file by running this command:
php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"
Now run the below command to generate JWT secret key like:
php artisan jwt:secret
This command will update your .env file like this:
JWT_SECRET=TIfwzvlyoyDLMTnuYvZ771DeYcv0HmJvyFgajlGezgWU0cekfY0dLGJfvoL3AkjE
JWT_ALGO=HS256
STEP 4: CONFIGURING API GUARD
Now in this step, we have to update and set up the API authentication guard. So update the following file like that:
config/auth.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_reset_tokens',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
STEP 5: UPDATE USER MODEL
Now all are set to go. Now we have to update the User model like below. So update it to create laravel jwt auth:
app\Models\User.php
<?php
namespace App\Models;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
STEP 6: CREATE CONTROLLER
Now we have to create AuthController to complete our JWT authentication with a refresh token in Laravel 10. So run the below command to create a controller:
php artisan make:controller API/AuthController
Now update this controller like this:
<?php
namespace App\Http\Controllers\API;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
]);
$credentials = $request->only('email', 'password');
$token = Auth::attempt($credentials);
if (!$token) {
return response()->json([
'message' => 'Unauthorized',
], 401);
}
$user = Auth::user();
return response()->json([
'user' => $user,
'authorization' => [
'token' => $token,
'type' => 'bearer',
]
]);
}
public function register(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
return response()->json([
'message' => 'User created successfully',
'user' => $user
]);
}
public function logout()
{
Auth::logout();
return response()->json([
'message' => 'Successfully logged out',
]);
}
public function refresh()
{
return response()->json([
'user' => Auth::user(),
'authorisation' => [
'token' => Auth::refresh(),
'type' => 'bearer',
]
]);
}
}
STEP 7: CREATE ROUTE
Here, we need to add routes to set laravel generate jwt token and laravel 10 jwt authentication tutorial. So update the api routes file like this:
routes/api.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\AuthController;
Route::controller(AuthController::class)->group(function () {
Route::post('login', 'login');
Route::post('register', 'register');
Route::post('logout', 'logout');
Route::post('refresh', 'refresh');
});
Now if you start your server by running php artisan serve and test all API via Postman like this:
http://127.0.0.1:8000/api/register
http://127.0.0.1:8000/api/login
http://127.0.0.1:8000/api/refresh
http://127.0.0.1:8000/api/logout
Top comments (0)