Hello, laravel web developers! In this article, we'll see how to authenticate using JWT in laravel 11. In laravel 11, we use JSON web token(JWT) for authentication. JSON Web Token is a proposed Internet standard for creating data with optional signature and/or optional encryption whose payload holds JSON that asserts some number of claims.
JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.
JWT is commonly used for Authorization and Information Exchange.
How to Authenticate using JWT in Laravel 11
In this step, we'll install the laravel 11 application using the following composer command.
composer create-project laravel/laravel laravel-11-jwt-auth
Next, we'll configure the database to the .env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_11_auth
DB_USERNAME=root
DB_PASSWORD=root
Then, we'll enable API routes. Because in laravel 11 by default API routes are not enabled.
php artisan install:api
bootstrap/app.php
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->render(function (AuthenticationException $e, Request $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => $e->getMessage(),
], 401);
}
});
})->create();
Now, install jwt-auth using the following composer command.
composer require php-open-source-saver/jwt-auth
Publish the config file.
php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"
Next, generate a secret key and add JWT config values on .env
file.
php artisan jwt:secret
.env
JWT_SECRET=xxxxxxxx
config/auth.php
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Next, we'll update the User.php file. Implement PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject contract on the User Model and also add getJWTIdentifier() and getJWTCustomClaims() methods.
app/Models/User.php
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use 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',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
/**
* 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 [];
}
}
Then, we'll create a controller using the following command.
php artisan make:controller AuthController
app/Http/Controllers/AuthController.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
use Validator;
class AuthController extends Controller
{
/**
* Register a User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function register() {
$validator = Validator::make(request()->all(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed|min:8',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$user = new User;
$user->name = request()->name;
$user->email = request()->email;
$user->password = bcrypt(request()->password);
$user->save();
return response()->json($user, 201);
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
Next, we'll define the routes into the api.php file
routes/api.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('/register', [AuthController::class, 'register'])->name('register');
Route::post('/login', [AuthController::class, 'login'])->name('login');
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:api')->name('logout');
Route::post('/refresh', [AuthController::class, 'refresh'])->middleware('auth:api')->name('refresh');
Route::post('/me', [AuthController::class, 'me'])->middleware('auth:api')->name('me');
});
Now, run the laravel 11 application using the following command.
php artisan serve
You might also like:
In this article, we will see how to create a dynamic pie chart in laravel 9. Pie charts are used to repre...
Mar-20-2022
Hello developers! In this article, we'll see how to change the date format in laravel 11. Here, we'll learn...
Apr-29-2024
Hey there, Ever found yourself scratching your head over unexpected errors in your PHP code? Fret not, because today, we...
Dec-15-2023
In this artical, we will explain the laravel 9 file upload example step by step. As we know file upload is the most comm...
Mar-11-2022