Making Laravel Passport work with Lumen

Overview

lumen-passport

Build Status Code Climate Total Downloads Latest Stable Version Latest Unstable Version License

Making Laravel Passport work with Lumen

A simple service provider that makes Laravel Passport work with Lumen

Dependencies

  • PHP >= 5.6.3
  • Lumen >= 5.3

Installation via Composer

First install Lumen if you don't have it yet:

$ composer create-project --prefer-dist laravel/lumen lumen-app

Then install Lumen Passport (it will fetch Laravel Passport along):

$ cd lumen-app
$ composer require dusterio/lumen-passport

Or if you prefer, edit composer.json manually:

{
    "require": {
        "dusterio/lumen-passport": "^0.3.0"
    }
}

Modify the bootstrap flow (bootstrap/app.php file)

We need to enable both Laravel Passport provider and Lumen-specific provider:

// Enable Facades
$app->withFacades();

// Enable Eloquent
$app->withEloquent();

// Enable auth middleware (shipped with Lumen)
$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
]);

// Finally register two service providers - original one and Lumen adapter
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);

Using with Laravel Passport 7.3.2 and newer

Laravel Passport 7.3.2 had a breaking change - new method introduced on Application class that exists in Laravel but not in Lumen. You could either lock in to an older version or swap the Application class like follows at the top of your bootstrap/app.php file:

$app = new \Dusterio\LumenPassport\Lumen7Application(
    dirname(__DIR__)
);

If you look inside this class - all it does is adding an extra method configurationIsCached() that always returns false.

Migrate and install Laravel Passport

# Create new tables for Passport
php artisan migrate

# Install encryption keys and other necessary stuff for Passport
php artisan passport:install

Installed routes

This package mounts the following routes after you call routes() method (see instructions below):

Verb Path NamedRoute Controller Action Middleware
POST /oauth/token \Laravel\Passport\Http\Controllers\AccessTokenController issueToken -
GET /oauth/tokens \Laravel\Passport\Http\Controllers\AuthorizedAccessTokenController forUser auth
DELETE /oauth/tokens/{token_id} \Laravel\Passport\Http\Controllers\AuthorizedAccessTokenController destroy auth
POST /oauth/token/refresh \Laravel\Passport\Http\Controllers\TransientTokenController refresh auth
GET /oauth/clients \Laravel\Passport\Http\Controllers\ClientController forUser auth
POST /oauth/clients \Laravel\Passport\Http\Controllers\ClientController store auth
PUT /oauth/clients/{client_id} \Laravel\Passport\Http\Controllers\ClientController update auth
DELETE /oauth/clients/{client_id} \Laravel\Passport\Http\Controllers\ClientController destroy auth
GET /oauth/scopes \Laravel\Passport\Http\Controllers\ScopeController all auth
GET /oauth/personal-access-tokens \Laravel\Passport\Http\Controllers\PersonalAccessTokenController forUser auth
POST /oauth/personal-access-tokens \Laravel\Passport\Http\Controllers\PersonalAccessTokenController store auth
DELETE /oauth/personal-access-tokens/{token_id} \Laravel\Passport\Http\Controllers\PersonalAccessTokenController destroy auth

Please note that some of the Laravel Passport's routes had to 'go away' because they are web-related and rely on sessions (eg. authorise pages). Lumen is an API framework so only API-related routes are present.

Configuration

Edit config/auth.php to suit your needs. A simple example:

return [
    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],

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

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

Load the config in bootstrap/app.php since Lumen doesn't load config files automatically:

$app->configure('auth');

Registering Routes

Next, you should call the LumenPassport::routes method within the boot method of your application (one of your service providers). This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:

\Dusterio\LumenPassport\LumenPassport::routes($this->app);

You can add that into an existing group, or add use this route registrar independently like so;

\Dusterio\LumenPassport\LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']);

User model

Make sure your user model uses Passport's HasApiTokens trait, eg.:

class User extends Model implements AuthenticatableContract, AuthorizableContract
{
    use HasApiTokens, Authenticatable, Authorizable;

    /* rest of the model */
}

Extra features

There are a couple of extra features that aren't present in Laravel Passport

Allowing multiple tokens per client

Sometimes it's handy to allow multiple access tokens per password grant client. Eg. user logs in from several browsers simultaneously. Currently Laravel Passport does not allow that.

use Dusterio\LumenPassport\LumenPassport;

// Somewhere in your application service provider or bootstrap process
LumenPassport::allowMultipleTokens();

Different TTLs for different password clients

Laravel Passport allows to set one global TTL for access tokens, but it may be useful sometimes to set different TTLs for different clients (eg. mobile users get more time than desktop users).

Simply do the following in your service provider:

// Second parameter is the client Id
LumenPassport::tokensExpireIn(Carbon::now()->addYears(50), 2); 

If you don't specify client Id, it will simply fall back to Laravel Passport implementation.

Console command for purging expired tokens

Simply run php artisan passport:purge to remove expired refresh tokens and their corresponding access tokens from the database.

Running with Apache httpd

If you are using Apache web server, it may strip Authorization headers and thus break Passport.

Add the following either to your config directly or to .htaccess:

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

Video tutorials

I've just started a educational YouTube channel that will cover top IT trends in software development and DevOps: config.sys

Also I'm happy to announce my newest tool – GrammarCI, an automated (as a part of CI/CD process) spelling and grammar checks for your code so that your users don't see your typos :)

License

The MIT License (MIT) Copyright (c) 2016 Denis Mysenko

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Thanks!

    Thanks!

    Hi @dusterio

    This looks exactly like what I've been looking for. Was kind of surprised when I saw Passport wasn't working with Lumen out of the box - seems like that would be the first stop for it :)

    Anyway, I'm going to try out your package with the latest Lumen install on a production environment. We use a multi node setup, as I like to keep things separate and such. Please let me know if you need any help maintaining this project, code wise or anywhere else.

    Thanks again!

    opened by PCoetzeeDev 53
  • Auth guard driver [api] is not defined Error

    Auth guard driver [api] is not defined Error

    when I called /oauth/token/refresh or /oauth/tokens then its throw

    InvalidArgumentException in AuthManager.php line 99: Auth guard driver [api] is not defined.

    opened by rockers007 40
  • Choice question must have at least 1 choice available.

    Choice question must have at least 1 choice available.

    Getting LogicException: Choice question must have at least 1 choice available. ChoiceQuestion.php:36 error when running the php artisan passport:install command. Can you help with this please? steps:

    1. Creating new lumen project
    2. composer require dusterio/lumen-passport
    3. bootstrap/app.php configs
    4. php artisan migrate
    5. php artisan passport:install
    opened by HarutEnoqyan 29
  • routes not mounted

    routes not mounted

    Hi,

    I followed all the steps but the routes are not mounted there in lumen route folder? I didn't understand this line? I think I am doing something wrong after the passport:install command.

    "Adding this service provider, will mount the following routes:" What's the meaning of this line?

    opened by rajaunleashed 25
  • Tokens Expired, Access Still Allowed

    Tokens Expired, Access Still Allowed

    I think this maybe in the passport layer, however I am not completely sure.

    I have set both the ttl of the token and the fresh to 1, and 2 minutes. Then waited 5 minutes. I can still access the routes. This is a password grant, not that this should matter.

    opened by mrforsythexeter 22
  • OAuth routes not working

    OAuth routes not working

    Working with Lumen 5.4, fresh install. I followed all the steps until this part:

    'Next, you should call the LumenPassport::routes method within the boot method of your application.'

    I don't understand where I have to call this method, and the oauth routes are not working. I get a 'NotFoundHttpException' exception.

    I found this tutorial and there's no mention of this step, I also noticed that the version used is 0.1 and the latest one is 0.2. So I guess you changed something that makes this extra step needed.

    What I mean to say is that the documentation should be more specific for those of us who are not that familiar with laravel/lumen.

    opened by freddieRv 19
  • Issue in Lumen 5.6

    Issue in Lumen 5.6

    I am getting this error

    Unresolvable dependency resolving [Parameter #0 [ <required> $app ]] in class Illuminate\Support\Manager

    Can you please guide me how can i fix it

    opened by wasiqaftab 13
  • not support lumen 9

    not support lumen 9

    hi i have a error on lumen 9

    `LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']);

    Call to undefined method Laravel\Lumen\Application::group()

    `

    opened by Rasoul-Karimi 12
  • No longer works after release of laravel/passport v7.3.2 ( undefined method Laravel\Lumen\Application::configurationIsCached() error )

    No longer works after release of laravel/passport v7.3.2 ( undefined method Laravel\Lumen\Application::configurationIsCached() error )

    Lumen version 5.8.10 dusterio/lumen-passport version 0.2.11

    After composer update installed laravel/passport v7.3.2, my api crashes with the following error: Call to undefined method Laravel\Lumen\Application::configurationIsCached()

    Only fix I could come up with was to add "laravel/passport": "7.3.1" to my top level composer.json file.

    opened by picofaradpjf 12
  • Dependacy Issue on Lumen 6

    Dependacy Issue on Lumen 6

    When trying to run the composer command on Lumen 6 composer gives the following message:

    Your requirements could not be resolved to an installable set of packages.

    Problem 1 - Installation request for dusterio/lumen-passport ^0.2.14 -> satisfiable by dusterio/lumen-passport[0.2.14]. - Conclusion: remove illuminate/container v6.0.2 - Conclusion: don't install illuminate/container v6.0.2 - dusterio/lumen-passport 0.2.14 requires illuminate/database ~5.3|~5.4|~5.5|~5.6 -> satisfiable by illuminate/database[5.3.x-dev, 5.4.x-dev, 5.5.x-dev, 5.6.x-dev, 5.7.17, 5.7.18, 5.7.19, 5.7.x-dev, 5.8.x-dev, v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.13, v5.4.17, v5.4.19, v5.4.27, v5.4.36, v5.4.9, v5.5.0, v5.5.16, v5.5.17, v5.5.2, v5.5.28, v5.5.33, v5.5.34, v5.5.35, v5.5.36, v5.5.37, v5.5.39, v5.5.40, v5.5.41, v5.5.43, v5.5.44, v5.6.0, v5.6.1, v5.6.10, v5.6.11, v5.6.12, v5.6.13, v5.6.14, v5.6.15, v5.6.16, v5.6.17, v5.6.19, v5.6.2, v5.6.20, v5.6.21, v5.6.22, v5.6.23, v5.6.24, v5.6.25, v5.6.26, v5.6.27, v5.6.28, v5.6.29, v5.6.3, v5.6.30, v5.6.31, v5.6.32, v5.6.33, v5.6.34, v5.6.35, v5.6.36, v5.6.37, v5.6.38, v5.6.39, v5.6.4, v5.6.5, v5.6.6, v5.6.7, v5.6.8, v5.6.9, v5.7.0, v5.7.1, v5.7.10, v5.7.11, v5.7.15, v5.7.2, v5.7.20, v5.7.21, v5.7.22, v5.7.23, v5.7.26, v5.7.27, v5.7.28, v5.7.3, v5.7.4, v5.7.5, v5.7.6, v5.7.7, v5.7.8, v5.7.9, v5.8.0, v5.8.11, v5.8.12, v5.8.14, v5.8.15, v5.8.17, v5.8.18, v5.8.19, v5.8.2, v5.8.20, v5.8.22, v5.8.24, v5.8.27, v5.8.28, v5.8.29, v5.8.3, v5.8.30, v5.8.31, v5.8.32, v5.8.33, v5.8.34, v5.8.35, v5.8.4, v5.8.8, v5.8.9].

    opened by EntrepreneurAJ 9
  • '??' operator used in AccessTokenController@issueToken() (no support in PHP 5.X)

    '??' operator used in AccessTokenController@issueToken() (no support in PHP 5.X)

    In \dusterio\lumen-passport\src\Http\Controllers\AccessTokenController@issueToken() r. 26 is written the following: $clientId = ((array) $request->getParsedBody())['client_id'] ?? null;

    Which is introduced in last commit: https://github.com/dusterio/lumen-passport/commit/256aece42ea17ef8018d7de8392baa8affa647d5

    The ?? operator isn't supported in PHP versions lower then PHP 7, since it is introduced in PHP 7.0: http://php.net/manual/en/migration70.new-features.php

    Therefor the package is crashing instantly when calling (for example): POST /oauth/token endpoints

    Suggested fix, something in line of: $clientId = !is_null($request->getParsedBody()) ? $request->getParsedBody()['client_id'] : null;

    or increasing 'minimum supported php' to version 7 😄

    opened by DCdeBrabander 9
  • Restrictions with models

    Restrictions with models

    I'm working with this package, my project I force myself in rename the passport's tables and this issue I can resolved created a own provider as follows:

    <?php
    
    namespace App\Providers;
    
    use Laravel\Passport\Passport;
    use Dusterio\LumenPassport\PassportServiceProvider;
    use App\Models\{User, Token, Client, AuthCode, PersonalAccessClient, RefreshToken};
    
    class TelesaludServiceProvider extends PassportServiceProvider 
    { 
    
        public function boot()
        {
            
            Passport::useTokenModel(Token::class);
            Passport::useClientModel(Client::class);
            Passport::useAuthCodeModel(AuthCode::class);
            Passport::usePersonalAccessClientModel(PersonalAccessClient::class);
            Passport::useRefreshTokenModel(RefreshToken::class);
            
        }
    
    }
    

    Where each model in my project I haved to renamed the table as follows:

    <?php
    
    namespace App\Models;
    
    use Laravel\Passport\Token as TokenPassport;
    
    class Token extends TokenPassport 
    {
        /**
         * The database table used by the model.
         *
         * @var string
         */
        protected $table = 'telesa_oauth_access_tokens';
    }
    

    The problem is in this code:

    https://github.com/dusterio/lumen-passport/blob/9729c62dc3ccbcf4b31c173817223851f84cfd98/src/Http/Controllers/AccessTokenController.php#L95-L101

    https://github.com/dusterio/lumen-passport/blob/9729c62dc3ccbcf4b31c173817223851f84cfd98/src/Console/Commands/Purge.php#L35-L43

    So, your package call the table with the Passport original value, so if I make a print at Token::class I have: Laravel\Passport\Token when the correct behavior is get App\Model\Token

    I'm new in Lumel and Passport but I suppose this is the right way to can use different tables names

    opened by alejosv 0
  • Remove direct access to models

    Remove direct access to models

    AccessTokenController@revokeOrDeleteAccessTokens no longer access Token's model directly. It now uses Passport::token() instead. I also have added the feature to set what connection should be used for passport. You only need to set PASSPORT_CONNECTION in your .env file.

    opened by lucasctd 0
Releases(0.3.6)
Owner
Denis Mysenko
IT wizard, aikidoka and scuba diver. Also a Dj
Denis Mysenko
Laravel Passport Memoized

Laravel Passport comes with repositories for the underlying oauth2-server that result in multiple queries to retrieve the same exact object from the database in a single request. With a good database engine this will have a small impact in the range of milliseconds but this is still unacceptable and should be avoided if possible.

Alex Bouma 26 Aug 15, 2022
Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use

Introduction Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use. Official Documentation Documenta

The Laravel Framework 3.1k Dec 31, 2022
Integrate reCAPTCHA using async HTTP/2, making your app fast with a few lines

Integrate reCAPTCHA using async HTTP/2, making your app fast with a few lines

Laragear 14 Dec 6, 2022
An OAuth 2.0 bridge for Laravel and Lumen [DEPRECATED FOR LARAVEL 5.3+]

OAuth 2.0 Server for Laravel (deprecated for Laravel 5.3+) Note: This package is no longer maintaned for Laravel 5.3+ since Laravel now features the P

Luca Degasperi 2.4k Jan 6, 2023
A simple library to work with JSON Web Token and JSON Web Signature

JWT A simple library to work with JSON Web Token and JSON Web Signature based on the RFC 7519. Installation Package is available on Packagist, you can

Luís Cobucci 6.8k Jan 3, 2023
🔐 JSON Web Token Authentication for Laravel & Lumen

Documentation Documentation for 1.* here For version 0.5.* See the WIKI for documentation. Supported by Auth0 If you want to easily add secure authent

Sean Tymon 10.7k Dec 31, 2022
JWT auth for Laravel and Lumen

JWT Artisan Token auth for Laravel and Lumen web artisans JWT is a great solution for authenticating API requests between various services. This packa

⑅ Generation Tux ⑅ 141 Dec 21, 2022
🔐 JSON Web Token Authentication for Laravel & Lumen

Credits This repository it a fork from original tymonsdesigns/jwt-auth, we decided to fork and work independent because the original one was not being

null 490 Dec 27, 2022
An invisible reCAPTCHA package for Laravel, Lumen, CI or native PHP.

Invisible reCAPTCHA Why Invisible reCAPTCHA? Invisible reCAPTCHA is an improved version of reCAPTCHA v2(no captcha). In reCAPTCHA v2, users need to cl

Albert Chen 578 Nov 30, 2022
🔑 Simple Keycloak Guard for Laravel / Lumen

Simple Keycloak Guard for Laravel / Lumen This package helps you authenticate users on a Laravel API based on JWT tokens generated from Keycloak Serve

Robson Tenório 277 Jan 3, 2023
HTTP Basic Auth Guard for Lumen 5.x

HTTP Basic Auth Guard HTTP Basic Auth Guard is a Lumen Package that lets you use basic as your driver for the authentication guard in your application

Christopher Lass 40 Nov 11, 2022
Authentication REST-API built with Lumen PHP Framework

Authentication REST-API built with Lumen PHP Framework Laravel Lumen is a stunningly fast PHP micro-framework for building web applications with expre

Hüseyin Yağlı 1 Oct 12, 2021
A Laravel 5 package for OAuth Social Login/Register implementation using Laravel socialite and (optionally) AdminLTE Laravel package

laravel-social A Laravel 5 package for OAuth Social Login/Register implementation using Laravel socialite and (optionally) AdminLTE Laravel package. I

Sergi Tur Badenas 42 Nov 29, 2022
:octocat: Socialite is an OAuth2 Authentication tool. It is inspired by laravel/socialite, you can easily use it without Laravel.

Socialite Socialite is an OAuth2 Authentication tool. It is inspired by laravel/socialite, You can easily use it in any PHP project. 中文文档 This tool no

安正超 1.2k Dec 22, 2022
A Simple method to create laravel authentication for an existing laravel project.

Laravel Simple Auth A Simple method to create laravel authentication for an existing laravel project. Indroduction Why I created this kind of package?

Dasun Tharanga 10 Dec 14, 2021
Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system.

Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system. Built on Bootstrap 4.

Jeremy Kenedy 2.8k Dec 31, 2022
Handle roles and permissions in your Laravel application

Laratrust (Laravel Package) Version Compatibility Laravel Laratrust 8.x 6.x 7.x 6.x 6.x 6.x 5.6.x - 5.8.x 5.2 5.3.x - 5.5.x 5.1 5.0.x - 5.2.x 4.0. Ins

Santiago García 2k Dec 30, 2022
Role-based Permissions for Laravel 5

ENTRUST (Laravel 5 Package) Entrust is a succinct and flexible way to add Role-based Permissions to Laravel 5. If you are looking for the Laravel 4 ve

Zizaco 6.1k Jan 5, 2023
Roles & Permissions for Laravel 8 / 7 / 6 / 5

Defender Defender is an Access Control List (ACL) Solution for Laravel 5 / 6 / 7 (single auth). (Not compatible with multi-auth) With security and usa

Artesãos 437 Dec 22, 2022