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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • API and Security: From IT to Cyber
  • When APIs Go Wrong: Neglecting Rate Limiting
  • Secure Your API With JWT: Kong OpenID Connect
  • API Security: Best Practices and Patterns To Securing APIs

Trending

  • Automatic Code Transformation With OpenRewrite
  • How to Convert XLS to XLSX in Java
  • Integrating Security as Code: A Necessity for DevSecOps
  • A Complete Guide to Modern AI Developer Tools
  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 user avatar
Razet Jain
·
Jan. 09, 21 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
19.3K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • API and Security: From IT to Cyber
  • When APIs Go Wrong: Neglecting Rate Limiting
  • Secure Your API With JWT: Kong OpenID Connect
  • API Security: Best Practices and Patterns To Securing APIs

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!