PHP code example of gboyegadada / lumen-jwt

1. Go to this page and download the library: Download gboyegadada/lumen-jwt library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gboyegadada / lumen-jwt example snippets


# edit: bootstrap/app.php

// 1. Uncomment next 2 lines...
$app->withFacades();
$app->withEloquent();

// 2. Uncomment next 3 lines...
$app->routeMiddleware([
     'auth' => App\Http\Middleware\Authenticate::class,
]);

// 3. Register Auth Service Provider
$app->register(Yega\Auth\JWTAuthServiceProvider::class);


# edit: config/auth.php

/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
| ........
|
*/

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

/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
| ..............
|
*/

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model'  => App\Models\User::class,
    ]
],


# edit: routes/web.php

// Wrap protected routes with this...
$app->group(['middleware' => 'auth:api' ], function($app)  {
    // Protected route...
    $app->get('test', function (Request $request) use ($app) {
        return "Yayyy! I'm so safe! Not!"
    });
});


# edit: app/Http/Controllers/AuthController.php

/**
 * post: /login
 * @return string
 */
public function postLogin(Request $req)
{

    $credentials = $req->only('email', 'password');

    /**
     * Token on success | false on fail
     *
     * @var string | boolean
     */
    $token = Auth::attempt($credentials);

    return ($token !== false)
            ? json_encode(['jwt' => $token])
            : response('Unauthorized.', 401);

}