Hướng dẫn cài đặt và test Laravel Sanctum

Setup:
Update composer:

composer self-update --2

Setup laravel project:

composer create-project laravel/laravel demo

Setup sanctum

composer require laravel/sanctum

Copy file config:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

Setup database:
Tạo database tên demo
Edit file .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=demo
DB_USERNAME=root
DB_PASSWORD=

Create database:

php artisan migrate

Thêm vào User model

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

Thêm vào file app/Http/Kernel.php

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

Tạo 3 controller:

php artisan make:controller UserController
php artisan make:controller LoginController
php artisan make:controller RegisterController

Tạo folder Auth trong folder Controllers và copy 2 file LoginController.php và RegisterController.php vào folder Auth
Sửa file route/api.php thành như sau:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/logout', 'App\Http\Controllers\UserController@logout')->name('logout.api');
    Route::get('/user', 'App\Http\Controllers\UserController@userdata')->name('user.api');
});


Route::post('/register', 'App\Http\Controllers\Auth\RegisterController@register');
Route::post('/login', 'App\Http\Controllers\Auth\LoginController@login');

Thêm function register trong RegisterController

Thêm function login vào LoginController

Thêm function userdata và logout vào UserController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;

class UserController extends Controller
{
    public function userdata(Request $request){
        return $request->user();
    }

    public function logout(){
        Auth::user()->token()->delete();
        return response()->json([
                'status_code' => 200,
                'message' => 'Logout successfull',
            ]);
    }
}

Test với Postman
Register
Link:localhost/demo/public/index.php/api/register
Method:post

Login and get token key:
Link:localhost/demo/public/index.php/api/login
Method:post
Ta nhận được api token:
“access_token”: “1|vPcr38WXqPEAa03fxYjLccAXpT5jRPB419rOEuPb”

Test get user data with token key:
To do this on postman, click on the Headers tab, and add a new key ‘Accept’ and type the value ‘application/json’

Link:localhost/demo/public/index.php/api/user
Method:get
Truyền token vào:

Result

Link code in here

Leave a Reply

avatar
  Subscribe  
Notify of