How to Create an authentication API in Laravel? Best and easy way create Laravel authentication API, Laravel API authentication in few steps

Create authentication API in Laravel

Written By: Mohamed Atef

Published: 2022-04-22 | Comments: 0 | Category: Laravel

How to create Laravel API authentication?

Hello everyone, Welcome to Web-Brackets.com, in this article I am going to show you How to create Laravel Authentication API in few steps

The first step install Laravel passport

You can install Laravel passport using this command below, from my vision Laravel passport is the best way to use API authentication in Laravel 9x because a lot of packages like JWT are not compatible with the Laravel version 9

composer require laravel/passport

one the command above is done, you will need to run the migration again to create tables for the authentication

php artisan migrate

then you can generate Passport tokens using 

php artisan passport:install

Be careful that every time you run the migration command or fresh the migration using any of these commands php artisan migrate:fresh or php artisan migrate you will need to run the command of generating the tokens (php artisan passport:install)

Then open the app.php config file and make sure that there is a guard called API with driver passport

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => true,
        ],
    ],

and then in AuthServiceProvider.php add Passport::routes();

<?php

namespace App\Providers;

//Import Passport 
use Laravel\Passport\Passport;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot(){
        $this->registerPolicies();
        //Add passport routes
        Passport::routes();
    }
}

then I will start a controller called users_controller so I can add the login method to get a token 

php artisan make:controller authentication/users_controller

and we can use the Laravel Tinker to register a new user

php artisan tinker
\App\Models\User::create([ "name" => "Mohamed atef", "email" => "test@test.com", "password" => bcrypt("password123") ]);

Note that you can modify the user table from database/migrations/"search about user table probably the first one"

the login function will be 

    public function login(Request $req){
        $validator = Validator::make($req->all(), [
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }

        if(Auth::guard('api')->attempt(['email' => request('email') , 'password' => request('password')])){
            $token = Auth::guard('api')->user()->createToken('auth_token')->accessToken;
            $lastLogin = User::find(Auth::guard('api')->user()->id);
            $lastLogin->last_login = Carbon::now()->format('Y-m-d\TH:i:s.vP');
            $lastLogin->save();
            return response()->json([ "user" => Auth::guard('api')->user(), "token" => $token ], 200);
        } else {
            return response()->json(['Error'], 400);    
        }
    }

Note that the line below is responsible for generating the access token using Laravel passport 

$token = Auth::guard('api')->user()->createToken('auth_token')->accessToken;

Now we can create routes for the login in the file called api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\authentication\users_controller;

Route::middleware('auth:api')->get('/user', function (Request $request){
    return $request->user();
});

Route::controller(users_controller::class)->prefix('/user')->group(function (){
    Route::post('/login', 'login');
});

?>

Using Thunder Client (VSCode extension like Postman) I will generate a POST request on the login endpoint http://127.0.0.1:8000/api/user/login

 

Comments

There is no comments yet

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Authenticated PDF or Images with Laravel API
Publish date: 2022-04-23 | Comments: 0