Creating API authentication with Laravel Passport

Introduction

API stands for Application Programming Interface. It is a code or interface in Java that allows fluid communication between software or programs, in this case using the same packages. RESTful APIs are essential for modern JavaScript frameworks or for building mobile apps. The user needs tokens for application authorization or authentication. In the case of software development, the API handles data through HTTP requests and handles CRUD operations.

Laravel is a platform that makes API creation extremely easy. By using the Laravel passport, one can quickly secure the backend of applications by authenticating users via the API. In the API ecosystem, one does not maintain session state between requests. This article will guide you step by step to provide an extra layer of security to your Laravel APIs.

Laravel Passport: what is it?

In simple words, Laravel Passport is an API authentication package and OAuth2 server. It is a platform that contains a substantial amount of boilerplate codes for user authentication. To implement the packages, including functions to generate tokens, migration tables, or Middleware authentication, it is only necessary to adjust some basic configurations in Laravel’s passport platform. Software companies have a demand for people with extensive knowledge of Laravel and are hoping to hire Laravel developers.

Requirements:

  • COMPOSER: installed globally to manage dependencies
  • POSTMAN – to test endpoints
  • Basic knowledge of building applications.

Laravel Passport Installation:

  • For Laravel Passport installation, first, you need to run the mentioned.

domain:

composer requires laravel/passport

  • Once the passport package installation is successful, the next step is passport migration to store the tokens in new tables.
See also  Integration of IT consulting in the healthcare sector to drive organizational efficiency

php craft migration

  • After the tables are migrated, running the following command will fully install it.

php artisan passport: install

  • Code for the configuration of the passport module; you must open the app/Models/User.php file to include the HasApiTokens trait in the user model.

In the next section we will configure the passport authentication route controller.

  • You must add the Passport::routes method in the AuthServiceProvider to generate the necessary routes. We can specify the default lifetime expiration date for personal access tokens that we are issuing to users using the boot() function.
  • We need to configure passport as the API authentication guard. By modifying config/auth.php, from now on all applications can use Passport’s TokenGuard to authenticate all incoming API requests.
  • Our primary focus is to ensure that only authenticated users can access the specified paths. To focus on this aspect, you should secure the /user and /logout endpoints and keep the /login and /signup endpoints publicly accessible.

Next, we’ll create routes by adding routes in the route/api.php file.

We also need to create an API controller for the REST API in Laravel.

  • For this purpose, we need to run the Artisan command mentioned below to create a new controller.

🌕 php craft creation: ApiController.php controller

<?php

namespace App\Http\Controllers\Auth;

use App\User;use App\Traits\ApiResponser;use Illuminate\Http\Request;use Laravel\Passport\Passport;use App\Http\Controllers\Controller;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades \Hash;

class AuthController extends Controller{use ApiResponser;

public function login(Request $request) { $attr = $this->validateLogin($request);

if (!Auth::attempt($attr)) {return $this->error(‘Credentials mismatch’, 401);}

returns $this->token($this->getPersonalAccessToken());}

public function signup(Request $request) { $attr = $this->validateSignup($request);

User::create([‘name’ => $attr[‘name’],’mail’ => $attribute[’email’],’password’ => Hash::make($attr[‘password’])]);

Authorization::attempt([’email’ => $attr[’email’]’password’ => $attribute[‘password’]]);

See also  Is Windows 11 Free: How to Upgrade Windows 10 to Windows 11 Easily?

return $this->token($this->getPersonalAccessToken(), ‘Created by user’, 201);}

public function user(){return $this->success(Auth::user());}

public function logout(){Auth::user()->token()->revoke();return $this->success(‘User Logout’, 200);}

public function getPersonalAccessToken(){ if (request()->remember_me === ‘true’)Passport::personalAccessTokensExpireIn(now()->addDays(15));

returns Auth::user()->createToken(‘Personal access token’);}

public function validateLogin($request){return $request->validate([’email’ => ‘required|string|email|max:255’,‘password’ => ‘required|string|min:6’,]);}

public function validateRecord($request){return $request->validate([‘name’ => ‘required|string’,’email’ => ‘required|string|email|max:255|unique:users’,‘password’ => ‘required|string|min:6|confirmed’,]);}}

Here, in the signup() function, you need to create a new user according to the requested data by validating the provided data.

  • To generate a token, we can call a getPersonalAccessToken() function.

The token lifetime can be extended when we set the value of remember_me to ‘true’.

  • Since Passport Middleware protects the /user endpoint, we will always have access to the Auth::user() function.

Once we’ve successfully created a controller for authentication, it’s time to test the REST API. You can use a virtual host for testing or test it on the PHP development server.

In general, we use tools like Postman to test our API endpoints.

To start this process, you will need to start by getting an access token for an already registered user. You can send a GET request to “API/login” by passing the email and password as parameters. If you are not registered,

  • API Registration: Open the Postman application and set “Accept”: application/JSON
  • Login Passport API – Used to copy the bearer token and set it in the application header section. To log in, you’ll need to check the Laravel passport endpoint.
  • We need to establish precise authenticity to execute CRUD operations. You will receive an access token after a successful registration. The manifestation of this access token establishes consistency with the authorization to guarantee the secure transmission of data with the server.
See also  Adobe's new AI photo editing tool could be the future of photo editing

You must save the access token as a

Bearer token in the authorization header.

Conclusion

Finally, we have completed the Laravel Passport API tutorial. You can follow all the basic steps outlined to build on top of this and design a secure API using the Laravel passport. Mastering this secure API development process in Laravel Passport can ensure you get hired as a Laravel developer. Errors can arise at any step, depending on the code and your application, but through an ongoing process of trial and error, a secure API can be developed quickly.

Subscribe to our latest newsletter

To read our exclusive content, sign up now. $5/month, $50/year

Categories: Technology
Source: vtt.edu.vn

Leave a Comment