Bảo mật Lumen với Passport

1.Cài đặt Lumen:

composer create-project --prefer-dist laravel/lumen lumen_blog "5.4.*"

Tạo database tên :lumen
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
DB_USERNAME=root
DB_PASSWORD=

CACHE_DRIVER=file
QUEUE_DRIVER=sync

2.Cài đặt Lumen Passport

composer require dusterio/lumen-passport "^0.2.0"

Edit file bootstrap/app.php như sau:

// Enable Facades
$app->withFacades();
// Enable Eloquent
$app->withEloquent();
...
// Enable auth middleware (shipped with Lumen)
$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
]);
...
// Finally register two service providers - original one and Lumen adapter
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);

3.Tiếp theo migrate và install Laravel Passport

# Create new tables for Passport
php artisan migrate
# Install encryption keys and other necessary stuff for Passport
php artisan passport:install

Tạo thư mục config ở root folder và tạo file config/auth.php

<?php
return [
    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],
'guards' => [
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => \App\User::class
        ]
    ]
];

Tiếp theo edit file bootstrap/app.php thêm vào

$app->configure('auth');

File boostrap/app.php hoàn chỉnh như sau:

Tiếp theo mở file app/Providers/AuthServiceProvider.php thêm vào boot function

LumenPassport::routes($this->app);

AuthServiceProvider.php hoàn chỉnh:

Tiếp theo edit file app/User.php

use Laravel\Passport\HasApiTokens;
...
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
    use HasApiTokens, Authenticatable, Authorizable;
/* rest of the model */
}

Cập nhật $fillable thêm ‘password’ field.

protected $fillable = [
        'name', 'email', 'password'
 ];

Tạo file UsersController.php

Thêm route routes/web.php:

$app->post('/register','UsersController@register');

Tạo table users:

php artisan make:migration create_table_users_table --create=users

Thêm field:

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->string('password');
            $table->timestamp('last_logged_in')->nullable();
           $table->timestamps();
 });

Run:

php artisan migrate

Open your Postman post method with url:http://localhost/lumen_blog/public/index.php/register

Sau khi đã get được token ta test access với token
Thêm vào route/web.php

$app->group(['prefix' => 'api'], function () use ($app) {
    $app->get('/', function () use ($app) {
        return "API is working.";
    });

    $app->group(['middleware' => 'auth'], function () use ($app) {
        $app->get('/testapi', 'DemoController@testapi');
    });
});

Tạo DemoController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DemoController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }


    public function testapi(){
        echo 'test api';
    }
}

Tiếp theo mở postman with Authorization key with Bearer {access_token}
get method with url:http://localhost/lumen_blog/public/index.php/api/testapi

Link source code here

0 Shares

Leave a Reply

avatar
  Subscribe  
Notify of