PHP code example of agungsugiarto / codeigniter4-authentication-jwt

1. Go to this page and download the library: Download agungsugiarto/codeigniter4-authentication-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/ */

    

agungsugiarto / codeigniter4-authentication-jwt example snippets


namespace App\Entities;

//..
use Fluent\JWTAuth\Contracts\JWTSubjectInterface;

class User extends Entity implements
    //..
    JWTSubjectInterface
{
    /**
     * {@inheritdoc}
     */
    public function getJWTIdentifier()
    {
        return $this->id;
    }

    /**
     * {@inheritdoc}
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

namespace App\Providers;

use Fluent\Auth\AbstractServiceProvider;
use Fluent\Auth\Facades\Auth;
use Fluent\JWTAuth\Config\Services;
use Fluent\JWTAuth\JWTGuard;

class AuthServiceProvider extends AbstractServiceProvider
{
    /**
     * {@inheritdoc}
     */
    public static function register()
    {
        Auth::extend(JWTGuard::class, function ($auth, $name, array $config) {
            return new JWTGuard(
                Services::getSharedInstance('jwt'),
                Services::getSharedInstance('request'),
                $auth->createUserProvider($config['provider']),
            );
        });
    }
}

public $guards = [
    //..
    'api' => [
        'driver' => \Fluent\JWTAuth\JWTGuard::class,
        'provider' => 'users',
    ],
];

Events::on('pre_system', [\App\Providers\AuthServiceProvider::class, 'register']);

$routes->group('jwt', function ($routes) {
    $routes->post('login', 'JwtauthController::login');
    $routes->post('logout', 'JwtauthController::logout', ['filter' => 'auth:api']);
    $routes->post('refresh', 'JwtauthController::refresh', ['filter' => 'auth:api']);
    $routes->match(['get', 'post'], 'user', 'JwtauthController::user', ['filter' => 'auth:api']);
});



namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;

class JwtauthController extends BaseController
{
    use ResponseTrait;

    /**
     * Get a JWT via given credentials.
     *
     * @return \CodeIgniter\Http\Response
     */
    public function login()
    {
        // Validate this credentials request.
        if (! $this->validate(['email' => '
    }

    /**
     * Get the authenticated User.
     *
     * @return \CodeIgniter\Http\Response
     */
    public function user()
    {
        return $this->response->setJson(auth('api')->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \CodeIgniter\Http\Response
     */
    public function logout()
    {
        auth('api')->logout();

        return $this->response->setJson(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \CodeIgniter\Http\Response
     */
    public function refresh()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \CodeIgniter\Http\Response
     */
    protected function respondWithToken($token)
    {
        return $this->response->setJson([
            'access_token' => $token,
            'token_type'   => 'bearer',
            'expires_in'   => auth('api')->factory()->getTTL() * 60,
        ]);
    }
}

 $token = auth('api')->attempt($credentials);

// Generate a token for the user if the credentials are valid
$token = auth('api')->attempt($credentials);

// Get some user from somewhere
$user = (new UserModel())->first();

// Get the token
$token = auth('api')->login($user);

// Get the currently authenticated user
$user = auth('api')->user();

try {
    $user = auth('api')->userOrFail();
} catch (\Fluent\JWTAuth\Exceptions\UserNotDefinedException $e) {
    // do something
}

auth('api')->logout();

// Pass true to force the token to be blacklisted "forever"
auth('api')->logout(true);

$newToken = auth('api')->refresh();

// Pass true as the first param to force the token to be blacklisted "forever".
// The second parameter will reset the claims for the new token
$newToken = auth('api')->refresh(true, true);

auth('api')->invalidate();

// Pass true as the first param to force the token to be blacklisted "forever".
auth('api')->invalidate(true);

$token = auth('api')->tokenById(123);


$payload = auth('api')->payload();

// then you can access the claims directly e.g.
$payload->get('sub'); // = 123
$payload['jti']; // = 'asfe4fq434asdf'
$payload('exp') // = 123456
$payload->toArray(); // = ['sub' => 123, 'exp' => 123456, 'jti' => 'asfe4fq434asdf'] etc

if (auth('api')->validate($credentials)) {
    // credentials are valid
}

$token = auth('api')->claims(['foo' => 'bar'])->attempt($credentials);

$user = auth('api')->setToken('eyJhb...')->user();

$user = auth('api')->setRequest($request)->user();

$token = auth('api')->setTTL(7200)->attempt($credentials);
sh
php spark make:controller JwtauthController