HTTP Basic Auth Guard for Lumen 5.x

Overview

HTTP Basic Auth Guard

Latest Version on Packagist Software License Total Downloads

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

The Guard brings back the missing stateless HTTP Basic Authentication possibilities for Lumen >=5.2.

Explanation

As of Lumen 5.2 the session storage is not included anymore.
Unfortunately, for calling Auth::onceBasic(), Auth::basic(), or alike you'll need the session driver which requires the session storage.
Therefore HTTP Basic Authentication does not work out-of-the-box anymore for Lumen >=5.2.
To be honest, I have no idea why Taylor Otwell removed this functionality from Lumen 5.2.
My best guess is, that he doesn't even know since my issue got closed instantly on github 😃
Luckily, this package brings the usual functionality back!

Requirements

  • Lumen 5.2 or above Installation.
  • Note: For Laravel 5.* or Lumen 5.1 HTTP Basic Auth still works out-of-the-box with the session driver: Link.

Tested with

  • Lumen 5.2, 5.3, 5.4, 5.5, 5.6, 5.7
  • PHP 5.6, 7.0, 7.1, 7.2, 7.3

Current master is for Lumen >= 5.7. For Lumen <= 5.6 Use version ^1.0.

Installation

1. Pull in package

$ composer require arubacao/http-basic-auth-guard

2. Read & Follow Official Lumen Documentation for Authentication

https://lumen.laravel.com/docs/5.7/authentication

Important:

Before using Lumen's authentication features, you should uncomment the call to register the AuthServiceProvider service provider in your bootstrap/app.php file.

// bootstrap/app.php

// Uncomment the following line 
 $app->register(App\Providers\AuthServiceProvider::class);

Of course, any routes you wish to authenticate should be assigned the auth middleware, so you should uncomment the call to $app->routeMiddleware() in your bootstrap/app.php file:

// bootstrap/app.php

// Uncomment the following lines
 $app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
 ]);

If you would like to use Auth::user() to access the currently authenticated user, you should uncomment the $app->withFacades() method in your bootstrap/app.php file.

// bootstrap/app.php

// Uncomment the following lines
 $app->withFacades();
 $app->withEloquent();

3. Add the Service Provider

Open bootstrap/app.php and register the service provider:

// bootstrap/app.php

// Add the following line
$app->register(Arubacao\BasicAuth\BasicGuardServiceProvider::class);

4. Setup Guard Driver

Note: In Lumen you first have to copy the config file from the directory vendor/laravel/lumen-framework/config/auth.php, create a config folder in your root folder and finally paste the copied file there.

$ mkdir config
$ cp vendor/laravel/lumen-framework/config/auth.php config/

Open your config/auth.php config file.
In guards add a new key of your choice (api in this example).
Add basic as the driver.
Make sure you also set provider for the guard to communicate with your database.

// config/auth.php
'guards' => [
    'api' => [
        'driver' => 'basic',
        'provider' => 'users'
    ],

    // ...
],

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

Usage

Middleware protecting the route:

Route::get('api/whatever', ['middleware' => 'auth:api', 'uses' => 'NiceController@awesome']);

Middleware protecting the controller:

<?php

namespace App\Http\Controllers;

class NiceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }
}

Change log

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Any issues, feedback, suggestions or questions please use issue tracker here.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

License

The MIT License (MIT).

Analytics

Comments
  • Can't use/how to use several middlewares with your guard and can't use/how to use several guards near

    Can't use/how to use several middlewares with your guard and can't use/how to use several guards near

    Hello! I've found your implementation, and was interested to use it with Lumen, after updating from 5.1 to 5.3 version. I was scratching my head for a long time, wondering how to use token authorization (I use jwt) for several routes and how to use actually basic authorization for api routes. I was using basic authorization with sessions previously likewise. Everything worked fine, but there were some reasons to update, and get rid off sessions. When I started to use your guard, everything seemed clear. I added few guards, and used them differently with routes. That was good, except the moment of using several middlewares one by one with this guard. I believe that's because your guard doesn't have state, and it doesn't remember the user, like it was with sessions. So I want to ask you - have you try such case? And have you thought about few middlewares with such authorization guard?

    opened by c0nst4nt 6
  • Auth::basic() always does Auth::onceBasic()

    Auth::basic() always does Auth::onceBasic()

    The basic() method triggers check(), which triggers user() in return, which triggers onceBasic() (since commit https://github.com/arubacao/http-basic-auth-guard/commit/372eb687dada13d9428c770371ba67d0cb71f373). This means if you run Auth::basic() it will always do Auth::onceBasic() first (with the default parameters). If this passes, it will never get to logging in. Is this on purpose?

    My goal is to make sure the Illuminate\Auth\Events\Login event gets triggered, so I can check if $user->is_active === true - and return a 401 Unauthorized if it's false.

    Is there a better way to this? Shouldn' the login/logout events be triggered, even on onceBasic? Maybe trigger the Logout event at the end of the request? To keep the statelessness of the basic authentication.

    Thanks for the great package btw!

    bug 
    opened by mauvm 4
  • Unauthorized on every route protected using middleware

    Unauthorized on every route protected using middleware

    I setup a fresh 5.4 Lumen application. I then uncommented the following lines in my bootstrap/app.php:

    $app->withFacades();
    $app->withEloquent()
    [...]
    $app->routeMiddleware([
        'auth' => App\Http\Middleware\Authenticate::class,
    ]);
    [...]
    $app->register(App\Providers\AppServiceProvider::class);
    $app->register(App\Providers\AuthServiceProvider::class);
    $app->register(Arubacao\BasicAuth\BasicGuardServiceProvider::class);
    

    Next, I added jwt-auth-1.0.0-beta-2 to my application using the composer require. Added the below line to my AppServiceProvider:

    this->app->register(\Tymon\JWTAuth\Providers\LumenServiceProvider::class);
    

    and did the php artisan jwt:secret step.

    The following is my web.php router:

    $app->group(['prefix' => 'api'], function($app){
        $app->post('/signup', [
            'uses' => 'UserController@Signup'
        ]);
    
        $app->group(['middleware' => 'auth:jwt-auth'], function($app){
            $app->post('/logout',[
    	    'uses' => 'UserController@LogoutUser'
    	]);
        });
    });
    

    In my UserContoller.php, this is what I do:

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Http\Controllers\Controller;
    use Illuminate\Http\Request;
    use Tymon\JWTAuth\JWTAuth;
    use App\User;
    use Tymon\JWTAuth\Exceptions\JWTException;
    
    class UserController extends Controller
    {
    
        /**
         * @var \Tymon\JWTAuth\JWTAuth
         */
        protected $jwt;
    
        public function __construct(JWTAuth $jwt)
        {
            $this->jwt = $jwt;
        }
    
        public function Signin(Request $request)
        {
            try {
                if (!$token = $this->jwt->attempt($request->only('email', 'password'))) {
                    return response()->json(['The credentials provided are invalid.'], 404);
                }
            }  catch (JWTException $e){
                return response()->json([
                    'message' => 'We could not sign you in. Try again later.'
                ], 500);
            }
    
            return response()->json(compact('token'));
        }
    
        public function LogoutUser(Request $request){
            $token = $this->jwt->getToken();
    
            if($this->jwt->invalidate($token)){
                return response()->json([
                    'message' => 'User logged off successfully!'
                ], 200);
            } else {
                return response()->json([
                    'message' => 'Failed to logout user. Try again.'
                ], 500);
            }
        }
    
    }
    

    Now the problem is I can access the signup route and generate the jwt token. But, when I try to do a logout it says unauthorized. I have various other routes under the same middleware and all of them say the same.

    opened by newkillerbeast2017 3
  • call_user_func_array() expects parameter 1 to be a valid callback

    call_user_func_array() expects parameter 1 to be a valid callback

    Hi,

    Thank you for writing this package. I've followed the installation instructions (install package, register BasicGuardServiceProvider in bootstrap/app.php), however when I associate the basic driver to the api guard and update the routes.php file to use the auth:api middleware I receive the following

    call_user_func_array() expects parameter 1 to be a valid callback, class     
    'Arubacao\BasicAuth\BasicGuard' does not have a method 'handle'
    

    I'm using version 1.0.1 of the package, and Lumen 5.2.7. Application otherwise running fine.

    Any ideas?

    Thank you! Jason

    opened by wjgilmore 2
  • Username password field config

    Username password field config

    There's currently no way to change what fields the basic auth system is checking for username password combinations. Would it be possible to allow this to be configurable?

    opened by ZeroThe2nd 1
  • Sessions

    Sessions

    Can you add sessions to your project? Is it possible to use illuminate/session or something similar with your basic auth guard?

    Maybe something like this? http://qiita.com/mikakane/items/faa8becc85631be13156 Or maybe add support for this? https://packagist.org/packages/cuidong/lumen

    opened by NotJustPizza 1
Releases(2.0.0)
Owner
Christopher Lass
Christopher Lass
🔑 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
Stateless HTTP basic auth for Laravel without the need for a database.

Laravel Very Basic Auth Documentation available in: ???? English ???? 日本語 This package allows you to add a HTTP Basic Auth filter on your routes, with

Marcus Olsson 141 Dec 31, 2022
Multi Auth and admin auth in Laravel Project

Laravel Multi Auth For Complete Documentation, visit Here This package is just create admin side (multi auth), which is totaly isolated from your norm

Bitfumes 435 Dec 31, 2022
CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

Cake Development Corporation 24 Sep 23, 2022
A Native PHP MVC With Auth. If you will build your own PHP project in MVC with router and Auth, you can clone this ready to use MVC pattern repo.

If you will build your own PHP project in MVC with router and Auth, you can clone this ready to use MVC pattern repo. Auth system is implemented. Works with bootstrap 5. Composer with autoload are implemented too for future composer require.

null 2 Jun 6, 2022
Configurable Basic Auth based on Pimcore Documents

CORS Property Basic Auth This bundles allows to add basic auth based on Properties on Pimcore Documents. Simply use these properties password_enabled

CORS GmbH 1 Nov 12, 2021
Keycloak Web Guard for Laravel allow you authenticate users with Keycloak Server

Keycloak Web Guard for Laravel This packages allow you authenticate users with Keycloak Server. It works on front. For APIs we recommend laravel-keycl

YDigital Media 0 May 20, 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
PSR-7 and PSR-15 HTTP Basic Authentication Middleware

PSR-7 and PSR-15 Basic Auth Middleware This middleware implements HTTP Basic Authentication. It was originally developed for Slim but can be used with

Mika Tuupola 430 Dec 30, 2022
Google Auth Library for PHP

This is Google's officially supported PHP client library for using OAuth 2.0 authorization and authentication with Google APIs.

Google APIs 1.2k Jan 4, 2023
Set up Laravel Auth guards using Eloquent in seconds

Nightguard Set up Auth guards using Eloquent in seconds. Introduction Laravel guards provide a super convenient way of authorizing different areas of

Luke Downing 10 Mar 18, 2021
Laravel starter kit with Livewire & Bootstrap 5 auth scaffolding.

Laravel Livewire Auth Laravel starter kit with Livewire & Bootstrap 5 auth scaffolding. Requirements NPM Installation Create a new Laravel app: larave

null 8 Sep 11, 2021
Sliding captcha for dcat-admin auth / dcat-admin登陆 滑动验证插件 多平台支持

dcat-admin登陆 滑动验证插件 多平台支持 dcat-admin登陆 滑动验证插件 多平台支持 另有 laravel-admin版 Demo演示 演示站点(暂时无,目前地址为laravel-admin版的演示地址) 支持(按照字母顺序) 顶象 ✔️ 极验 ✔️ hCaptcha(和谷歌Rec

塵世不再 38 Dec 17, 2022
Files Course Laravel Micro Auth and Authorization

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

EspecializaTi 8 Oct 22, 2022
Simple JWT Auth support for Laravel PHP Framework

Laravel JWT Simple JWT Auth for Laravel PHP Framework using Firebase JWT under the hood. Installation Standard Composer package installation: composer

Ricardo Čerljenko 34 Nov 21, 2022
Simple PASETO Auth support for Laravel PHP Framework

Laravel PASETO Simple PASETO Auth for Laravel PHP Framework using paragonie/paseto under the hood. Installation Standard Composer package installation

Ricardo Čerljenko 9 Jan 11, 2022
Light-weight role-based permissions system for Laravel 6+ built in Auth system.

Kodeine/Laravel-ACL Laravel ACL adds role based permissions to built in Auth System of Laravel 8.0+. ACL middleware protects routes and even crud cont

Kodeine 781 Dec 15, 2022
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
Laravel auth-boilerplate using sanctum

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Jigar Bhaliya 3 Mar 2, 2022