DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Your API Authentication Isn’t Broken; It’s Quietly Failing in These 6 Ways
  • The ID That Costs Millions: Why API Authorization Failures Keep Winning
  • Understanding Custom Authorization Mechanisms in Amazon API Gateway and AWS AppSync
  • Secrets in Code: Understanding Secret Detection and Its Blind Spots

Trending

  • The Self-Hosting Math Changed While We Were Still Arguing About Sovereignty
  • How an AI Software Factory Works: From Developer Intent to Production
  • GenAI Security Gateway: An End-to-End Architecture
  • LangChainGo vs Genkit Go: Where Genkit Shines

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Databases
  4. Create API Authentication With Laravel Passport

Create API Authentication With Laravel Passport

Learn how to setup and configure Laravel Passport for API Authentication and RESTful APIs in a Laravel application.

By 
Razet Jain
·
Jan. 09, 21 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
19.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In this tutorial, we will see how to use Laravel passport authentication in your Laravel application. 

Let’s see how to setup and configure Laravel Passport for API authentication and RESTful APIs in a Laravel application.

Creating a New Project

Shell
 




x


 
1
composer create-project --prefer-dist laravel/laravel passport


Install Package

Shell
 




xxxxxxxxxx
1


 
1
composer require laravel/passport


Service Provider

You need to add Service Provider in the config/app.php file. So, open the file and add the Service Provider in the providers array.

PHP
 




xxxxxxxxxx
1


 
1
'providers' => [
2
    ....
3
    Laravel\Passport\PassportServiceProvider::class,
4
]


Migration and Installation

Set up database credentials in the .env file. Run the migration command to migrate schemas to your database.

Shell
 




xxxxxxxxxx
1


 
1
php artisan migrate


Next, it is required to install passport using the command below. It will generate encryption keys required to generate secret access tokens.

PHP
 




xxxxxxxxxx
1


 
1
php artisan passport:install


Passport Configure

Add Laravel\Passport\HasApiTokens trait to your User model. It will provide few helper methods.

Java
 




xxxxxxxxxx
1
30


 
1
<?php
2
 
3
namespace App;
4
 
5
use Illuminate\Notifications\Notifiable;
6
use Illuminate\Foundation\Auth\User as Authenticatable;
7
use Laravel\Passport\HasApiTokens;
8
 
9
class User extends Authenticatable
10
{
11
    use HasApiTokens, Notifiable;
12
 
13
    /**
14
     * The attributes that are mass assignable.
15
     *
16
     * @var array
17
     */
18
    protected $fillable = [
19
        'name', 'email', 'password',
20
    ];
21
 
22
    /**
23
     * The attributes that should be hidden for arrays.
24
     *
25
     * @var array
26
     */
27
    protected $hidden = [
28
        'password', 'remember_token',
29
    ];
30
}


Add Passport::routes method in the boot method of your AuthServiceProvider. It will generate necessary routes. This is how the app/Providers/AuthServiceProvider.php will look like after changes.

Java
 




xxxxxxxxxx
1
30


 
1
<?php
2
 
3
namespace App\Providers;
4
 
5
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
6
use Laravel\Passport\Passport;
7
 
8
class AuthServiceProvider extends ServiceProvider
9
{
10
    /**
11
     * The policy mappings for the application.
12
     *
13
     * @var array
14
     */
15
    protected $policies = [
16
        'App\Model' => 'App\Policies\ModelPolicy',
17
    ];
18
 
19
    /**
20
     * Register any authentication / authorization services.
21
     *
22
     * @return void
23
     */
24
    public function boot()
25
    {
26
        $this->registerPolicies();
27
 
28
        Passport::routes();
29
    }
30
}


In the config/auth.php file, set driver to the passport.

Java
 




xxxxxxxxxx
1
17


 
1
return [
2
    ....
3
 
4
    'guards' => [
5
        'web' => [
6
            'driver' => 'session',
7
            'provider' => 'users',
8
        ],
9
 
10
        'api' => [
11
            'driver' => 'passport',
12
            'provider' => 'users',
13
        ],
14
    ],
15
 
16
    ....
17
]


Create Route

Add routes in the routes/api.php file.

Java
 




xxxxxxxxxx
1


 
1
Route::post('login', 'PassportController@login');
2
Route::post('register', 'PassportController@register');
3
 
4
Route::middleware('auth:api')->group(function () {
5
    Route::get('user', 'PassportController@details');
6
 
7
    Route::resource('products', 'ProductController');
8
});


Create Controller for Authentication

Create Passport Controller by running the following command.

Shell
xxxxxxxxxx
1
 
1
php artisan make:controller PassportController

Copy the contents below to app/Http/Controllers/PassportController.php

Java
 




xxxxxxxxxx
1
65


 
1
<?php
2
 
3
namespace App\Http\Controllers;
4
 
5
use App\User;
6
use Illuminate\Http\Request;
7
 
8
class PassportController extends Controller
9
{
10
    /**
11
     * Handles Registration Request
12
     *
13
     * @param Request $request
14
     * @return \Illuminate\Http\JsonResponse
15
     */
16
    public function register(Request $request)
17
    {
18
        $this->validate($request, [
19
            'name' => 'required|min:3',
20
            'email' => 'required|email|unique:users',
21
            'password' => 'required|min:6',
22
        ]);
23
 
24
        $user = User::create([
25
            'name' => $request->name,
26
            'email' => $request->email,
27
            'password' => bcrypt($request->password)
28
        ]);
29
 
30
        $token = $user->createToken('TutsForWeb')->accessToken;
31
 
32
        return response()->json(['token' => $token], 200);
33
    }
34
 
35
    /**
36
     * Handles Login Request
37
     *
38
     * @param Request $request
39
     * @return \Illuminate\Http\JsonResponse
40
     */
41
    public function login(Request $request)
42
    {
43
        $credentials = [
44
            'email' => $request->email,
45
            'password' => $request->password
46
        ];
47
 
48
        if (auth()->attempt($credentials)) {
49
            $token = auth()->user()->createToken('TutsForWeb')->accessToken;
50
            return response()->json(['token' => $token], 200);
51
        } else {
52
            return response()->json(['error' => 'UnAuthorised'], 401);
53
        }
54
    }
55
 
56
    /**
57
     * Returns Authenticated User Details
58
     *
59
     * @return \Illuminate\Http\JsonResponse
60
     */
61
    public function details()
62
    {
63
        return response()->json(['user' => auth()->user()], 200);
64
    }
65
}


Testing

Now thar our logic is complete, let’s start testing. We will be testing it on PHP development server, but you can use virtual host if you want. Run the following command to serve the application on the PHP development server.

Shell
 
xxxxxxxxxx
1
 
1
php artisan serve

Now, let’s test our API endpoints using an API testing tool like Postman.

API Laravel authentication

Published at DZone with permission of Razet Jain. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Your API Authentication Isn’t Broken; It’s Quietly Failing in These 6 Ways
  • The ID That Costs Millions: Why API Authorization Failures Keep Winning
  • Understanding Custom Authorization Mechanisms in Amazon API Gateway and AWS AppSync
  • Secrets in Code: Understanding Secret Detection and Its Blind Spots

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook