Laravel Auth guard for FusionAuth JWT

Overview

Laravel FusionAuth JWT

Latest Version on Packagist Total Downloads GitHub Actions

Implement an Auth guard for FusionAuth JWTs in Laravel.
It ships with also a middleware to check against the user role.

Installation

You can install the package via composer:

composer require danilopolani/laravel-fusionauth-jwt

Then publish its config file:

php artisan vendor:publish --tag=fusionauth-jwt-config

Configuration

There are a few notable configuration options for the package.

Key Type Description
domain String Your FusionAuth domain, e.g. auth.myapp.com or sandbox.fusionauth.io.
client_id String The Client ID of the current application.
client_secret String The Client Secret of the current application.
issuers Array A list of authorized issuers for the incoming JWT.
audience String | Null The ID/Name of the authorized audience. If null, the Client ID will be used.
supported_algs Array The supported algorithms of the JWT. Supported: RS256 and HS256.
default_role String | Null The default role to be checked if you're using the CheckRole middleware.

Usage

To start protecting your APIs you need to add the Guard and the Auth Provider to your config/auth.php configuration file:

'guards' => [
    // ...
    'fusionauth' => [
        'driver' => 'fusionauth',
        'provider' => 'fusionauth',
    ],
],

'providers' => [
    // ...
    'fusionauth' => [
        'driver' => 'fusionauth',
    ],
],

Then you can use the auth:fusionauth guard to protect your endpoints; you can apply it to a group or a single route:

// app\Http\Kernel.php

protected $middlewareGroups = [
    'api' => [
        'auth:fusionauth',
        // ...
    ],
];

// or routes/api.php

Route::get('users', [UserController::class, 'index'])
    ->middleware('auth:fusionauth');

Now requests for those endpoints will check if the given JWT (given as Bearer token) is valid.

To retrieve the current logged in user - or to check if it's logged in - you can use the usual Auth facade methods, specifying the fusionauth guard:

Auth::guard('fusionauth')->check();

/** @var \DaniloPolani\FusionAuthJwt\FusionAuthJwtUser $user */
$user = Auth::guard('fusionauth')->user();

Role middleware

The package ships with a handy middleware to check for user role (stored in the roles key).

You can apply it on a middleware group inside the Kernel.php or to specific routes:

// app\Http\Kernel.php

protected $middlewareGroups = [
    'api' => [
        'auth:fusionauth',
        \DaniloPolani\FusionAuthJwt\Http\Middleware\CheckRole::class,
        // ...
    ],
];

// or routes/api.php

Route::get('users', [UserController::class, 'index'])
    ->middleware(['auth:fusionauth', 'fusionauth.role']);

By default the middleware will check that the current user has the default_role specified in the configuration file, but you can use as well a specific role, different from the default:

// routes/api.php

Route::get('users', [UserController::class, 'index'])
    ->middleware(['auth:fusionauth', 'fusionauth.role:admin']);

For more complex cases we suggest you to take a look on how the CheckRole middleware is written (using the RoleManager class) and write your own.

Usage in tests

When you need to test your endpoints in Laravel, you can take advantage of the actingAs method to set the current logged in user.

You can pass any property you want to the FusionAuthJwtUser class, like email, user etc. Take a look at this example where we specify the user roles:

use DaniloPolani\FusionAuthJwt\FusionAuthJwtUser;

$this
    ->actingAs(
        new FusionAuthJwtUser([
            'roles' => ['user', 'admin'],
        ]),
        'fusionauth',
    )
    ->get('/api/users')
    ->assertOk();

If you need to set the authenticated user outside HTTP testing (therefore you can't use actingAs()), you can use the setUser() method of the Auth facade:

use DaniloPolani\FusionAuthJwt\FusionAuthJwtUser;
use Illuminate\Support\Facades\Auth;

Auth::guard('fusionauth')->setUser(
    new FusionAuthJwtUser([
        'roles' => ['user', 'admin'],
    ])
);

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

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

Credits

License

The MIT License (MIT). Please see License File for more information.

Laravel Package Boilerplate

This package was generated using the Laravel Package Boilerplate.

You might also like...
Security Defense for Firebase's PHP-JWT Library

PHP-JWT-Guard Protect your code from being impacted by issue 351 in firebase/php-jwt. Installation First, install this library with Composer: composer

Rest API - JWT - Symfony5

Symfony5 JWT - REST API Example Symfony5 JWT - REST API Example Built With PHP Symfony 5 PostgreSQL Getting Started This is an example of how you may

PSR-7 and PSR-15 JWT Authentication Middleware

PSR-7 and PSR-15 JWT Authentication Middleware This middleware implements JSON Web Token Authentication. It was originally developed for Slim but can

PHP package for JWT

PHP-JWT A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to RFC 7519. Installation Use composer to manage your dependenc

Single file PHP that can serve as a JWT based authentication provider to the PHP-CRUD-API project

Single file PHP that can serve as a JWT based authentication provider to the PHP-CRUD-API project

JSON Web Token (JWT) for webman plugin
JSON Web Token (JWT) for webman plugin

JSON Web Token (JWT) for webman plugin Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。

Sistema de Administrativo - Cliente e Vendedor - Autenticação JWT e Relacionamentos  BD
Sistema de Administrativo - Cliente e Vendedor - Autenticação JWT e Relacionamentos BD

Hi there, My name is ATTILA SAMUELL TABORY, I love technology 👋 Sistema Administrativo Laravel e Vue JS - JWT e Relacionamentos BD Sistema Administra

Aplicação criada com Slim Framework com objetivo de criar autenticação com JWT e aprender sobre o framework Slim

Slim JWT App Essa aplicação tem como foco o aprendizado do Framework Slim e também a utilização de JWT. Como rodar a Aplicação A aplicação está config

JWT Authenticator for symfony

HalloVerdenJwtAuthenticatorBundle This bundle provides a JWT authenticator for Symfony applications. It's using PHP JWT Framework for parsing and vali

Comments
  • Config error

    Config error

    I followed the README but got this error:

    Argument 2 passed to DaniloPolani\\FusionAuthJwt\\FusionAuthJwtServiceProvider::DaniloPolani\\FusionAuthJwt\\{closure}() must be an instance of DaniloPolani\\FusionAuthJwt\\FusionAuthJwtUserProvider, null given
    

    Any Idea?

    opened by celyes 3
Releases(v2.0.0)
Owner
Theraloss
Senior Software Engineer & Tech Lead in love with Laravel and cats. Oh, almost forgot, I also work with Node, Vue, Angular, Ionic and much more.
Theraloss
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
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
A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready

A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready.

Damiano Petrungaro 58 Aug 10, 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
🔑 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
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
Probando JWT en Laravel

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

SelsiusRC28 1 Nov 2, 2021
Laravel JWT-Authentication API starter kit for rapid backend prototyping.

Laravel JWT API A Laravel JWT API starter kit. Features Laravel 8 Login, register, email verification and password reset Authentication with JWT Socia

Oybek Odilov 3 Nov 6, 2022