Laravel passport authentication api

 First install passport using below command

composer require laravel/passport



After that, rum migrate command 

php artisan migrate

Next, we need to install passport using below command

php artisan passport:install

.Now open users.php and add use Laravel\Passport\HasApiTokens;  If your model is already using the Laravel\Sanctum\HasApiTokens trait, you may remove that trait.

users.php

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'first_name',
        'last_name',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Now open config/auth.php file and define below array

'api' => [
'driver' => 'passport',
'provider' => 'users',
],


auth.php
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session"
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

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

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that each reset token will be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];


Now open route/api.php file
api.php
<?php

use App\Http\Controllers\api\AuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

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

Route::prefix('user')->group(function () {
    Route::post('register', [AuthController::class, 'register']);
    Route::post('login',[AuthController::class,'login']);
});

Route::middleware('auth:api')->group(function(){
    Route::post('user/logout',[AuthController::class,'logout']);
});

Now create a UserRegisterRequest.php using below command
php artisan make:request UserRegisterRequest

UserRegisterRequest.php
<?php

namespace App\Http\Requests;

use App\Helpers\ResponseBuilder;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class UserRegisterRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
        return [
            'first_name' => 'required|min:3|max:18',
            'last_name' => 'required|min:3|max:18',
            'email' => 'required|unique:users,email|email',
            'password' => 'required|min:6|max:18|confirmed',
        ];
    }

    public function messages()
    {
        return [
            'first_name.required' => 'Please Enter First Name !',
            'last_name.required' => 'Please Enter Last Name !',
            'email.unique' => 'This email is already used !',
        ];
    }

    protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        throw new HttpResponseException(ResponseBuilder::error($validator->errors()->first(), 400));
    }
}


Now make Helpers folder inside the app folder
and create a ResponseBuilder.php inside the Helpers folder

ResponseBuilder.php
<?php


namespace App\Helpers;

use stdClass;
use Symfony\Component\HttpFoundation\Response as HttpResponse;

class ResponseBuilder
{

    private $status;

    private $msg = null;

    private $data = null;

    private $httpCode = 200;

    private $meta = null;

    private $link = null;

    private $authToken = null;

    public function __construct(bool $status)
    {
        $this->status = $status;
    }

    public static function success($data, $msg = null, $httpCode = 200): HttpResponse  {
        return self::asSuccess()
            ->withData($data)
            ->withMessage($msg)
            ->withHttpCode($httpCode)
            ->build();
    }

    public static function successWithPagination($query, $data, $msg = null, $httpCode = 200): HttpResponse  {
        return self::asSuccess()
            ->withData($data)
            ->withMessage($msg)
            ->withHttpCode($httpCode)
            ->withPagination($query)
            ->build();
    }

    public static function successWithToken($token, $data, $msg = null, $httpCode = 200): HttpResponse  {
        return self::asSuccess()
            ->withAuthToken($token)
            ->withData($data)
            ->withMessage($msg)
            ->withHttpCode($httpCode)
            ->build();
    }

    public static function error($msg, $httpCode, $data = null) {
        return self::asError()
            ->withData($data)
            ->withMessage($msg)
            ->withHttpCode($httpCode)
            ->build();
    }

    public static function asSuccess(): self
    {
        return new self(1);
    }

    public static function asError(): self
    {
        return new self(0);
    }

    public function withMessage(string $msg = null): self {
        $this->msg = $msg;

        return $this;
    }

    public function withData($data = null): self {
        $this->data = $data;

        return $this;
    }

    public function withHttpCode(int $httpCode = 200): self {
        $this->httpCode = $httpCode;

        return $this;
    }

    public function withPagination($query) {
        $this->meta = [
            'total_page' => $query->lastPage(),
            'current_page' => $query->currentPage(),
            'total_item' => $query->total(),
            'per_page' => (int)$query->perPage(),
        ];

        $this->link = [
            'next' => $query->hasMorePages(),
            'prev' => boolval($query->previousPageUrl())
        ];

        return $this;
    }

    public function withAuthToken(string $token = null) {
        $this->authToken = $token;

        return $this;
    }

    public function build(): HttpResponse {
        $response['status'] = $this->status;

        !is_null($this->msg) && $response['message'] = $this->msg;
        !is_null($this->authToken) && $response['token'] = $this->authToken;
        !is_null($this->data) && $response['data'] = $this->data;
        !is_null($this->meta) && $response['meta'] = $this->meta;
        !is_null($this->link) && $response['link'] = $this->link;

        return response($response, $this->httpCode);
    }
    public static function json($msg = "", $data = [], $http_status_code = 200, $errors = NULL, $headers = [])
    {
        if (empty($data)) {
            $data = new stdClass();
        }

        if (empty($errors)) {
            $errors = new stdClass();
        }

        $body = [
            "message" => $msg,
            "errors" => $errors,
            "data"  => $data,
        ];

        return response()->json($body, $http_status_code, $headers, JSON_UNESCAPED_UNICODE);
    }
}

Now update Controller.php
Controller.php
<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use stdClass;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    protected $errorStatus   = 500;
    protected $successStatus = 200;
    protected $validationStatus = 400;
    protected $unauthStatus  = 401;
    protected $notFoundStatus  = 404;
    protected $invalidPermission = 403;

    protected $response;

    public function __construct()
    {
        $this->response  = new stdClass();
    }
}

Now create a Auth/AuthtuthController.php
AuthtuthController.php
<?php

namespace App\Http\Controllers\api;

use App\Helpers\ResponseBuilder;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserRegisterRequest;
use App\Http\Resources\UserRegisterResource;
use App\Models\User;
use GuzzleHttp\Psr7\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use phpDocumentor\Reflection\DocBlock\Tags\Uses;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    public function register(UserRegisterRequest $request)
    {
        try {
            $data = $request->only(['first_name', 'last_name', 'email', 'password']);
            $data['password'] = Hash::make($request->password);
            $user = User::create($data);
            $this->response = new UserRegisterResource($user);
            return ResponseBuilder::success($this->response, "success", $this->successStatus);
        } catch (\Exception $e) {
            Log::error($e);
            return ResponseBuilder::error("error", $this->errorStatus);
        }
    }

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

            if ($validator->fails()) {
                return ResponseBuilder::error("error", $this->validator->errors()->first(), $this->validationStatus);
            }

            $user = User::where('email', $request->email)->first();
            $credential = $request->only(['email', 'password']);
            if (Auth::attempt($credential)) {
                $token = $user->createToken('app')->accessToken;
                $this->response = new UserRegisterResource($user);

                return ResponseBuilder::successWithToken($token, $this->response, "Login Success !");
            } else {
                return ResponseBuilder::error("Invalid password !", $this->errorStatus);
            }
        } catch (\Exception $e) {
            Log::erro($e);
            return ResponseBuilder::error('something is wrong', $this->errorStatus);
        }
    }

    public function logout()
    {
        $user = Auth::user()->token();
        $user->revoke();

        return ResponseBuilder::success(null, "Logout Successfully !", $this->successStatus);
    }
}

Now create a UserRegisterResource.php Using below command
php artisan make:resource UserRegisterResource
UserRegisterResource.php
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserRegisterResource extends JsonResource
{

    public function toArray($request)
    {
        return [
            "id" => $this->id,
            "first_name" => $this->first_name,
            "last_name" => $this->last_name,
            "email" => $this->email,
        ];
    }
}

Comments