PHP code example of iqbalatma / laravel-jwt-authentication
1. Go to this page and download the library: Download iqbalatma/laravel-jwt-authentication 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/ */
iqbalatma / laravel-jwt-authentication example snippets
use Iqbalatma\LaravelJwtAuthentication\Interfaces\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
public function getJWTIdentifier(): string|int
{
return $this->getKey();
}
public function getJWTCustomClaims(): array
{
return [];
}
}
return [
/*
|--------------------------------------------------------------------------
| JWT library guard
|--------------------------------------------------------------------------
|
| This is guard that set in auth, because inside library guard defined manually
| Auth::guard(config("jwt.guard"));
|
*/
"guard" => "jwt",
/*
|--------------------------------------------------------------------------
| Access token verifier
|--------------------------------------------------------------------------
|
| This is configuration to prevent xss attack by verified access token via cookie httpOnly
|
*/
"is_using_access_token_verifier" => true,
/*
|--------------------------------------------------------------------------
| JWT Sign in Algorithm
|--------------------------------------------------------------------------
|
| Algorithm for sign jwt token. This token is using encoder and decoder from
| https://github.com/firebase/php-jwt
|
*/
'algo' => env('JWT_ALGO', 'HS256'),
/*
|--------------------------------------------------------------------------
| JWT Private Key
|--------------------------------------------------------------------------
|
| This private key use for first priority of encoding and decoding jwt (signing)
| so if this key (private key) and (public key) exists, jwt will sign using
| this key pairs as first priority. If this key pairs does not exist, sign jwt will
| using jwt secret. If secret does not exist it will throw an error
|
*/
"jwt_private_key" => env("JWT_PRIVATE_KEY", null),
/*
|--------------------------------------------------------------------------
| JWT Public Key
|--------------------------------------------------------------------------
|
| This public key is part of key pairs for signing jwt token.
|
*/
"jwt_public_key" => env("JWT_PUBLIC_KEY", null),
/*
|--------------------------------------------------------------------------
| JWT Passphrase
|--------------------------------------------------------------------------
|
| This is passphrase use to get jwt private key that translate the key
| using this passphrase
|
*/
"jwt_passphrase" => env("JWT_PASSPHRASE", null),
/*
|--------------------------------------------------------------------------
| Secret
|--------------------------------------------------------------------------
|
| This is secret that used for encoding jwt. This secret use to validate signature
| Do not expose this jwt secret
|
*/
'secret' => env('JWT_SECRET', null),
/*
|--------------------------------------------------------------------------
| Access Token TTL
|--------------------------------------------------------------------------
|
| This is TTL (Time To Life) for access token. When token is expired, the token
| is already invalid. Access token using to access protected resource.
| Middleware that can accept this token is auth.jwt:access
| This TTL is in seconds
| Default 1 Hour
|
*/
'access_token_ttl' => env('JWT_TTL', 60 * 60),
/*
|--------------------------------------------------------------------------
| Refresh Token TTL
|--------------------------------------------------------------------------
|
| This is TTL (Time To Life) for refresh token. When token is expired, the token
| is already invalid. Refresh token using to regenerate access token and refresh token
| and revoke previous access token and refresh token.
| Middleware that can accept this token is auth.jwt:refresh
| This TTL is in seconds
| Default 7 Days
*/
'refresh_token_ttl' => env('JWT_REFRESH_TTL', 60 * 60 * 24 * 7),
/*
|--------------------------------------------------------------------------
| Refresh Token
|--------------------------------------------------------------------------
|
| Refresh token mechanism is how middleware check/get your refresh token
| there are two options (cookie / header)
|
|
| Refresh token key is key to get when middleware mechanism choose cookie, so this key
| is used to get cookie to set refresh token
|
*/
'refresh_token' => [
'key' => 'jwt_refresh_token',
'http_only' => true,
'path' => "/",
'domain' => null,
'secure' => true,
'same_site' => 'lax',
],
/*
|--------------------------------------------------------------------------
| Access Token Verifier
|--------------------------------------------------------------------------
|
| Access token verifier is used to prevent XSS attack by binding access token
| to this verifier, and make sure any stolen token cannot be used by attacker
|
|
*/
'access_token_verifier' => [
'key' => 'access_token_verifier',
'http_only' => true,
'path' => "/",
'domain' => null,
'secure' => true,
'same_site' => 'lax',
]
];
use Illuminate\Support\Facades\Route;
//jwt middleware that need refresh token
Route::post("refresh-token", function (){
//do refresh logic here
})->middleware("auth.jwt:REFRESH");
//jwt middleware that need access token
Route::middleware("auth.jwt:ACCESS")->group(function () {
Route::get("user", function () {
return response()->json([
"success" => true,
"user" => Auth::user()
]);
});
// and others route
});
use Illuminate\Support\Facades\Auth;
$credentials = [
"email" => "[email protected]",
"password" => "admin"
];
#this attempt method will return boolean when user validation success
Auth::attempt($credentials, true, true);
#first parameter for credential, second parameter to tell that authentication using cookie httpOnly, third parameter to get
#if you are using access token verifier by is_using_access_token_verifier = true, its mean you need to set
#access token in cookie httpOnly
return response()->json([
"access_token" => "...",
])->withCookie(getCreatedCookieAccessTokenVerifier("put your access token verifier here"));
#full example
public function authenticate(AuthenticateRequest $request): JsonResponse
{
$credentials = request(['username', 'password']);
if (!$token = Auth::attempt($credentials)) {
return response()->json(
["message" => "Invalid credentials."]
);
}
/** @var User $user */
$user = Auth::user();
/** @var User $user */
$user = Auth::user();
return response()->json(
[
"code" => "SUCCESS",
"message" => "Logged in successfully.",
"timestamp" => now(),
"payload" => [
"data" => [
"id" => $user->id,
"username" => $user->username,
"first_name" => $user->first_name,
"last_name" => $user->last_name,
"email" => $user->email,
"access_token" => Auth::getAccessToken(),
],
],
]
)
->withCookie(getCreatedCookieAccessTokenVerifier(Auth::getAccessTokenVerifier()))
->withCookie(getCreatedCookieRefreshToken(Auth::getRefreshToken()));
}
public function refresh(): JsonResponse
{
Auth::refreshToken(Auth::user());
/** @var User $user */
$user = Auth::user();
return response()->json(
[
"code" => "SUCCESS",
"message" => "Logged in successfully.",
"timestamp" => now(),
"payload" => [
"data" => [
"id" => $user->id,
"username" => $user->username,
"first_name" => $user->first_name,
"last_name" => $user->last_name,
"email" => $user->email,
"access_token" => Auth::getAccessToken()
],
],
]
)
->withCookie(getCreatedCookieAccessTokenVerifier(Auth::getAccessTokenVerifier()))
->withCookie(getCreatedCookieRefreshToken(Auth::getRefreshToken()));
}
use Illuminate\Support\Facades\Auth;
Auth::logout();
Auth::logout(true); #add parameter true for revoke both token pair (access and refresh)
use Illuminate\Support\Facades\Auth;
Auth::refreshToken(Auth::user());
use Illuminate\Support\Facades\Auth;
use App\Models\User;
$user = User::find(1);
Auth::login($user);
use Illuminate\Support\Facades\Auth;
use App\Models\User;
$credentials = [
"email" => "[email protected]",
"password" => "admin"
];
$user = User::query()->where("email", "[email protected]")->find();
Auth::attempt($credentials);
Auth::login($user);
Auth::getAccessToken(); #to get access token
Auth::getRefreshToken(); #to get refresh token
Auth::getAccessTokenVerifier(); #to get access token verifier
#if you are not using default guard, you need to specify the guard
Auth::guard("jwt")->getAccessToken();