jijihohococo/ichi-api-authentication

API Authentication for laravel

dev-master 2021-08-02 09:11 UTC

This package is auto-updated.

Last update: 2024-09-29 05:49:55 UTC


README

Since I had difficulties in using Laravel Passport due to the conflicts of PHP Version and League Oauth2 Library. I had the idea of developing my own API Authentication driver. This API Authentication library is developed without Oauth2. It is also my first time library development. The usage and library structure is really same as Laravel Passport's structure. It is aimed to use multiple API Authentication Guards in Laravel API Developments without facing difficulties that I had mentioned above. The development frame had took one week.

This library can be used for Laravel Version 5.6 to 8 with PHP Version 7.0 to above

License

This package is Open Source According to MIT license

Installing Library

composer require jijihohococo/ichi-api-authentication:dev-master

Before Using

You need to have "id" , "email" and "password" columns in your user table to use this library.

Using the library

To use the library, firstly we need to assign the guards like below code in "config/auth.php" of your Laravel Project.

'guards' => [
	'user_api' => [
		'driver' => 'ichi',
		'provider' => 'users',
		'hash' => false,
	],
]

And then we need to add User API Guard into Ichi API Database by the below code in terminal

php artisan ichi:client --password

After choosing the right guard for your user in terminal as you mentioned in your guard array of "config/auth.php", your User Model need to inherit this library functions by the inheritance as shown as below.

namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use JiJiHoHoCoCo\IchiApiAuthentication\HasApi;
class User extends Authenticatable{
	use HasApi;
}

The configuration is finished, you can override the database models of Ichi library with command line as shown as below.

php artisan vendor:publish --tag=ichi-migrations

You can also override the configurations of Ichi Library with command line as shown as below

php artisan vendor:publish --tag=ichi-config

You can test the registration of your token like below

$user= User::create([
	'name' => 'jiji' , 
	'email' => 'ji@gmail.com' ,
	'password' => Hash::make( 'password' )
]);
$token=$user->ichiToken();
return response()->json([
	'name' => $user->name ,
	'token' => $token->token ,
	'expired_at' => $token->expired_at ,
    'refresh_token' => $token->refreshToken ,
    'refreshTokenExpiredTime' => $token->refreshTokenExpiredTime
]);

You can test the login of your token like below

You need to make Accept => application/json and Authorization => Bearer {token} in your headers to make login actions.
Route::group(['middleware' => ['auth:user_api']], function() {
	Route::get('user_profile',function(){
		$user=\Auth::guard('user_api')->user();
		dd($user->name);
	});
});

You can revoke the login token as shown as below.

Route::group(['middleware' => ['auth:user_api']], function() {
    Route::get('user_logout',function(){
        $user=\Auth::guard('user_api')->user();
        $user->revoke();
        return response()->json([
            'message' => 'Log out successfully'
        ]);
    });

The default expiration time of token is 1 Year. You can customize this expiration time like below in "app/Providers/AuthServiceProvider.php"

Gate has no connection with our library.

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use JiJiHoHoCoCo\IchiApiAuthentication\Ichi;
class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        Ichi::setExpiredAt(now()->addDays(2));
    }

You can select all the tokens of selected User By

User::findOrFail(1)->getAllTokens();

You can delete the revoked tokens in command line as shown as below

php artisan ichi:remove --revoke

You can delete the expired tokens in command line as shown as below

php artisan ichi:remove --expired

Refresh Token

You can refresh token outside of authentication route like that with the headers Accept => application/json and refresh_token => Bearer {refreshToken}. You must refresh token when your token is expired when he/she is login.

Route::get('refresh_user_token',function(){
    $user=new User;
    $refreshToken=$user->refreshToken();
    return response()->json([
        'name' => $refreshToken->user->name ,
        'token' => $refreshToken->token ,
        'expired_at' => $refreshToken->expired_at ,
        'refresh_token' => $refreshToken->refreshToken ,
        'refreshTokenExpiredTime' => $refreshToken->refreshTokenExpiredTime
     ]);
});

The default expiration time of refresh token is 1 Year. You can customize this expiration time like below in "app/Providers/AuthServiceProvider.php"

Gate has no connection with our library.

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use JiJiHoHoCoCo\IchiApiAuthentication\Ichi;
class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        Ichi::setRefreshExpiredAt(now()->addDays(2));
    }

Revoke Other Tokens

You can make log out other devices Accept => application/json and Authroization => Bearer {token} (that token will not be revoked).

Route::group(['middleware' => ['auth:user_api']], function() {
Route::get('revoke_other_token',function(){
    $user=\Auth::guard('user_api')->user();
    $user->logOutOtherTokens();
    return response()->json([
        'message' => 'Logout other devices success'
    ]);
});
});

You can get the number of revoked tokens of each user

User::findOrFail(1)->revokedTokens();

Hope you enjoy!