Laravel auth with json web token
Tạo project laravel version 5.4
composer create-project --prefer-dist laravel/laravel laravel_jwt "5.4.*"
Tiếp theo đó, config lại file .env để kết nối đến cơ sở dữ liệu:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=YOUR_DB_NAME DB_USERNAME=YOUR_MYSQL_USERNAME DB_PASSWORD=YOUR_MYSQL_PASSWORD
Sửa file D:\xampp\htdocs\laravel_jwt\app\Providers\AppServiceProvider.php
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Schema; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { Schema::defaultStringLength(191); } /** * Register any application services. * * @return void */ public function register() { // } }
Tạo database:
php artisan migrate
Cài đặt JWT
Cài đặt
Để cài đặt JWT dùng câu lệnh composer sau:
composer require tymon/jwt-auth
Cập nhật file config/app.php
'providers' => [ .... Tymon\JWTAuth\Providers\LaravelServiceProvider::class, ], 'aliases' => [ .... 'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class, ],
Pulish file config của jwt:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
Config time token vĩnh viễn không hết hạn cho mobile app mở file config\jwt.php
Tìm line 104 Sửa
'ttl' => env('JWT_TTL', 60),
Thành
'ttl' => env('JWT_TTL', null),
Sửa required_claims
'required_claims' => [ 'iss', 'iat', //'exp', 'nbf', 'sub', 'jti', ],
Tạo key cho jwt:
php artisan jwt:secret
Sử dụng JWT trong laravel
Update User model
Open User.php and implement JWTSubject for the model
use Tymon\JWTAuth\Contracts\JWTSubject; class User extends Authenticatable implements JWTSubject
and add 2 methods in the model
public function getJWTIdentifier() { return $this->getKey(); } public function getJWTCustomClaims() { return []; }
File User.php hoàn chỉnh
<?php namespace App; use Tymon\JWTAuth\Contracts\JWTSubject; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable implements JWTSubject { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * 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 []; } }
Cấu hình Auth guard
Edit file config/auth.php
'defaults' => [ 'guard' => 'api', 'passwords' => 'users', ], ... 'guards' => [ 'api' => [ 'driver' => 'jwt', 'provider' => 'users', ], ],
Open Kernel.php then add in $routeMiddleware
'jwt.auth' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class, 'jwt.refresh' => \Tymon\JWTAuth\Http\Middleware\RefreshToken::class,
Thêm route
Route::post('register', 'AuthController@register'); Route::post('login', 'AuthController@login'); Route::group(['middleware' => ['auth:api']], function () { Route::get('user-info', 'AuthController@getUserInfo'); });
Tạo controller AuthController
php artisan make:controller AuthController
Content AuthController.php
Nào, giờ chúng ta hãy check API response bằng Postman.
Link đăng ký http://localhost/laravel_jwt/public/index.php/api/register
Đăng nhập
Link đăng nhập:http://localhost/laravel_jwt/public/index.php/api/login
Sau khi đăng nhập thành công, ta sẽ nhận được JWT token. Ví dụ của mình sẽ có dạng như này:
{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3RcL2xhcmF2ZWxfand0XC9wdWJsaWNcL2luZGV4LnBocFwvYXBpXC9sb2dpbiIsImlhdCI6MTYwOTE2MjA5MCwibmJmIjoxNjA5MTYyMDkwLCJqdGkiOiJ6MTBlb1BqaWFIdjNHU1lIIiwic3ViIjoyLCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.TyeUklirRmlsn1V5PN12x7fG8XNbVXH8xdQD0573CNM"}
Sử dụng bearer token để truy cập http://localhost/laravel_jwt/public/index.php/api/user-info
Link code github here
Leave a Reply