Bảo mật Lumen với JWT
1.Cài đặt Lumen:
composer create-project --prefer-dist laravel/lumen lumen_jwt_demo "5.4.*"
Tạo database tên :lumen_jwt_demo
Cấu hình file .env
APP_ENV=local APP_DEBUG=true APP_KEY=base64:trp5LQ9/TW85+17o0T7F0bZ/Ca1J9cIMgvyNIYl0k/g= APP_TIMEZONE=UTC DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=lumen_jwt_demo DB_USERNAME=root DB_PASSWORD= CACHE_DRIVER=file QUEUE_DRIVER=sync
2.Tạo user
Tạo migration cho bảng người dùng :
php artisan make:migration create_users_table
Thêm field:
Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('email')->unique()->notNullable(); $table->string('password'); $table->timestamps(); });
Run:
php artisan migrate
3.Cài đặt Lumen JWT
composer require tymon/jwt-auth
Để cho phép Middleware và Dịch vụ liên quan đến Xác thực / Cấp phép, hãy bỏ comment hoặc thêm các dòng này vào
bootstrap/app.php:
$app->withFacades(); // cho phép gọi các Class mà không cần phải đúng các namespace $app->withEloquent(); // cho phép sử dụng eloquent của Laravel $app->routeMiddleware([ 'auth' => App\Http\Middleware\Authenticate::class, ]); $app->register(App\Providers\AuthServiceProvider::class); $app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);
Tạo một key sẽ được sử dụng để tạo các mã thông báo:
php artisan jwt:secret
Tạo tệp để cấu hình dịch vụ Xác thực config/auth.php
Tạo tệp để định cấu hình dịch vụ JWT config/jwt.php:
Sửa User model(app/User.php)
Thêm routes/web.php
$app->group(['prefix' => 'api'], function () use ($app) { // Matches "/api/register $app->post('register', 'AuthController@register'); // Matches "/api/login $app->post('login', 'AuthController@login'); // Matches "/api/profile $app->get('profile', 'UserController@profile'); // Matches "/api/users/1 //get one user by id $app->get('users/{id}', 'UserController@singleUser'); // Matches "/api/users $app->get('users', 'UserController@allUsers'); });
Tạo file app/Http/Controllers/AuthController.php
use POSTMAN with route http://localhost/lumen_jwt_demo/public/index.php/api/register
Sửa app/Http/Controllers/Controller.php
<?php namespace App\Http\Controllers; use Laravel\Lumen\Routing\Controller as BaseController; use Illuminate\Support\Facades\Auth; class Controller extends BaseController { protected function respondWithToken($token) { return response()->json([ 'token' => $token, 'token_type' => 'bearer', 'expires_in' => Auth::factory()->getTTL() * 60 ], 200); } }
Use postman http://localhost/lumen_jwt_demo/public/index.php/api/login
Tạo UserController.php
Sử dụng token key được tạo bởi login
Test với http://localhost/lumen_jwt_demo/public/index.php/api/users
Link code demo here
Leave a Reply