Como implementar autenticação JWT no Laravel 12

Posted on: June 17, 2025 05:07 PM

Posted by: Renato

Categories: Laravel jwt autenticacao

Views: 89

How to Implement JWT Authentication in Laravel 12
 

  • Laravel: A PHP framework for building web applications, following the MVC (Model-View-Controller) architecture. It provides built-in tools for authentication, routing, databases, and more.
  • JWT (JSON Web Token): A secure way to transmit data between parties as a JSON object, commonly used for authentication. In Laravel, JWT is often used to create stateless authentication for APIs.

1.Installing the JWT-Auth Package

(install api : php artisan install:api)

Run the following command to install the JWT package:

composer require tymon/jwt-auth

After installation, publish the package configuration:

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

This will create a config/jwt.php file where you can customize the JWT settings.

2.Generate JWT Secret Key

Run the following command to generate a secret key:

php artisan jwt:secret

This key will be stored in your .env file:

JWT_SECRET=strong_secret_word

3. Configure the Authentication Guard

Modify the config/auth.php file and set the guard driver to jwt:

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

4. Modify the User Model

In app/Models/User.php (or app/User.php in older versions), implement the JWTSubject interface:

use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    /**
     * Get the identifier that will be stored in the JWT token.
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return an array with custom claims to be added to the JWT token.
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

5. Create Authentication Controller

Generate a new controller:

php artisan make:controller AuthController

Inside app/Http/Controllers/AuthController.php, implement the login, register, and logout functions:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class AuthController extends Controller
{
    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|confirmed',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        try {
            $token = JWTAuth::fromUser($user);
        } catch (JWTException $e) {
            return response()->json(['error' => 'Could not create token'], 500);
        }

        return response()->json([
            'token' => $token,
            'user' => $user,
        ], 201);
    }

    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        try {
            if (!$token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'Invalid credentials'], 401);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'Could not create token'], 500);
        }

        return response()->json([
            'token' => $token
            'expires_in' => auth('api')->factory()->getTTL() * 60,
        ]);
    }

    public function logout()
    {
        try {
            JWTAuth::invalidate(JWTAuth::getToken());
        } catch (JWTException $e) {
            return response()->json(['error' => 'Failed to logout, please try again'], 500);
        }

        return response()->json(['message' => 'Successfully logged out']);
    }

    public function getUser()
    {
        try {
            $user = Auth::user();
            if (!$user) {
                return response()->json(['error' => 'User not found'], 404);
            }
            return response()->json($user);
        } catch (JWTException $e) {
            return response()->json(['error' => 'Failed to fetch user profile'], 500);
        }
    }

    public function updateUser(Request $request)
    {
        try {
            $user = Auth::user();
            $user->update($request->only(['name', 'email']));
            return response()->json($user);
        } catch (JWTException $e) {
            return response()->json(['error' => 'Failed to update user'], 500);
        }
    }
}

6. Middleware

You can also create middleware to protect routes:

php artisan make:middleware JwtMiddleware

In app/Http/Middleware/JwtMiddleware.php, update the handle function:

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Exception;
use Illuminate\Http\Request;

class JwtMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        try {
            JWTAuth::parseToken()->authenticate();
        } catch (Exception $e) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $next($request);
    }
}

in Laravel 12, middleware registration has been moved to the bootstrap/app.php file.

    ->withMiddleware(function (Middleware $middleware) {
        //
        $middleware->alias([
            'jwt' => JwtMiddleware::class
        ]);
    })

7. Define API Routes

Open routes/api.php and add these routes:

<?php

use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return response()->json(['message' => 'Hello world!']);
});

Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);

Route::middleware('jwt')->group(function () {
    Route::get('/user', [AuthController::class, 'getUser']);
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::put('/user', [AuthController::class, 'updateUser']);
});

Define API Routes

se Postman or any API testing tool to test the following endpoints:

  • POST /register: Register a new user.
  • POST /login: Log in and get a JWT token.
  • GET /user: Fetch the authenticated user's details (requires JWT token).
  • POST /logout: Invalidate the JWT token.
  • POST /refresh: Refresh the JWT token.

Fonte: https://medium.com/@aliboutaine/how-to-implement-jwt-authentication-in-laravel-12-1e2ae878d5dc


2

Share

Donate to Site


About Author

Renato

Developer

Add a Comment

Blog Search


Categories

Laravel (227) PHP (151) linux (124) Variados (110) ubuntu (58) Dicas (58) developer (48) postgresql (45) database (44) sql (42) Docker (32) mysql (31) front-end (31) devops (26) webdev (24) programming (23) eloquent (19) aws (19) tecnologia (19) dba (18) OUTROS (17) backend (16) laravelphp (16) dev (12) debian (12) react (10) reactjs (10) 100DaysOfCode (10) git (10) javascript (9) nginx (9) inteligencia-artificial (9) PHP Swoole (9) node (9) linux-tools (8) Architecture (8) ciencia (7) github (7) vue (7) arquitetura (6) windows (6) api (6) vscode (6) nodejs (6) webservice (6) vim (6) jwt (6) apache (5) macox (5) s3 (5) servers (5) ia (5) authentication (5) reactnative (5) rest (5) DevSecOps (5) npm (4) openai (4) google (4) opensource (4) mariadb (4) jenkins (4) Kubernetes (4) gitlab (4) angular (4) autenticacao (4) shell (4) mongodb (4) query (4) Raspberry (4) angularjs (4) inteligenciadedados (4) Padrao de design (4) artigo (4) wsl (4) Swoole (4) lets-encrypt (4) db (3) politica (3) RabbitMQ (3) educacao (3) intel (3) CMS (2) sail (3) script (3) performance (3) js (3) mysqli (3) Black Hat (3) terminal (3) log (3) mac (3) fedora (3) containers (3) json (3) authorization (3) phpswoole (3) ddd (3) blade (3) hardware (3) tests (3) macos (3) web (2) jobs (3) websocket (3) ssh (3) bash (3) nvm (2) imagick (2) maps (2) colors (2) Passport (2) JQuery (2) phpfpm (2) autorizacao (2) monitoring (2) laptop (2) gnome (2) powerbi (2) telefonia (2) Python (2) Oauth2 (2) android (2) unix (2) magento (2) iot (2) ffmpeg (2) combustivel (2) webhook (2) microservices (2) Curisidades (2) Solid (2) zsh (2) Go (2) BigLinux (2) POO (2) LazyVim (2) gource (2) homeOffice (2) html (2) openswoole (2) artificialintelligence (2) security (2) bancodedados (2) tailwind (2) livros (2) Transcribe (2) ElonMusk (2) redis (2) claude (2) ArchLinux (2) java (2) saude (1) seguranca (2) auth (2) cron (2) phpunit (2) kube (2) multiple_authen (2) policia (2) neovim (2) golang (2) noticias (2) haru (1) dracula (1) TrabalhoEmEquipe (1) Brasil (1) queue (1) agi (1) llama (1) hotfix (1) economia (1) transcription (1) cache (1) Amazon (1) October (1) lumen (1) Hyperf (1) replication (1) faceapp (1) vala (1) cloudstack (1) rpi (1) apple (1) oracle (1) iode (1) ffaa (1) vpn (1) MeioAmbiente (1) firefox (1) composer (1) scheduling (1) Asahi (1) pendrive (1) microservice (1) front (1) cor (1) auth (1) modelagemdedados (1) k8s (1) gasolina (1) wsl2 (1) csv (1) soap (1) piada (1) KubeCon (1) zorin-os (1) spring-boot (1) backup (1) playwright (1) Deepin (1) storage (1) benchmark (1) networking (1) Swoole (1) biologia (1) node-red (1) LETSENCRYPT (1) Grunt (1) Diagramas (1) boot (1) tensorflow (1) bootstrap (1) nuance (1) historia (1) dropbox (1) traefik (1) bug (1) akitando (1) llm (1) htm (1) transformers (1) cavalotroia (1) odd (1) m1 (1) Error (1) cinnamon (1) repmgr (1) federal (1) ruby (1) AppSec (1) orm (1) ArquiteturaDeSoftware (1) Passwordless (1) memcached (1) flow (1) compression (1) athena (1) front (1) wine (1) covid19 (0) services (1) phpjasper (1) models (1) kali-linux (1) geojson (1) yarn (1) picpay (1) Monolith (1) banco (1) PNPM (1) Desenvolvedor (1) Structurizr (1) symfony (1) presenter (1) lider (1) guard (1) Hackers (1) Bots (1) pytorch (1) nuxt (1) liquid (1) ec2 (1) transaction (1) c4 (1) rancher (1) algoritimo (1) Observability (1) Elasticsearch (1) translate (1) certbot (1) Oh My Zsh (1) ibm (1) escopos (1) usb (1) ckeditor (1) API_KEY_GOOGLE_MAPS (1) Manjaro (1) vicuna (1) coding (1) rust (1) markdown (1) JasperReports (1) Fibonacci (1) community (1) Samurai (1) payment (1) messaging (1) Jesus (1) flutter (1) Migration (1) workflow (1) cqrs (1) kitematic (1) geospacial (1) yeshua (1) data (1) sonarqube (1) Axios (1) pipelines (1) Mozilla (1) kvm (1) GitOps (1) sqlite (1) podcast (1) n8n (1) LaravelFilament (1) God (1) DesenvolvimentoProfissional (1) sw (1) bigtech (1) postgres (1) NoCookies (1) LeetCode (1) governancadedados (1) prf (1) nosql (1) Lideranca (1) linkedin (1) documentation (1) brain (1) adb (1) nvidia (1) host (1) ecommerce (1) c4-models (1) altadisponibilidade (1) octane (1) lucena (1) http (1) TypeScript (1) chatgpt (1) idiomas (1) eventdrive (1) uuid (1) restfull (1) aplicativo (1) optimization (1) mapas (1) Fetch (1) collections (1) RustLang (1) matematica (1) Filament (1) compactar (1) paypal (1) microg (1) forcas armadas (1) militar (1) fullsta (1) smartphones (1) automacao (1) Monitor (1) zend (1) spaceship (1) PKCE (1) l2tp (1) Glacier (1) laraveloctane (1) Deus (1) binaural (1) gpt (1) bolsonaro (1) privacidade (1) OOD (0) controllers (0)

New Articles



Get Latest Updates by Email