├── .gitignore ├── .styleci.yml ├── .github ├── FUNDING.yml └── workflows │ └── main.yml ├── src ├── Exceptions │ ├── InvalidTokenException.php │ └── InvalidTokenAlgorithmException.php ├── Helpers │ └── RoleManager.php ├── Http │ └── Middleware │ │ └── CheckRole.php ├── FusionAuthJwtUserProvider.php ├── FusionAuthJwtServiceProvider.php ├── FusionAuthJwtUser.php └── FusionAuthJwt.php ├── .editorconfig ├── phpunit.xml ├── tests ├── Pest.php ├── Helpers │ └── RoleManagerTest.php ├── TestCase.php ├── FusionAuthJwtTest.php └── Middleware │ └── CheckRoleTest.php ├── LICENSE.md ├── composer.json ├── config └── fusionauth.php ├── CONTRIBUTING.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | vendor/ 2 | coverage/ 3 | composer.lock 4 | .DS_Store 5 | *.cache 6 | -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - single_class_element_per_statement 5 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: danilopolani 2 | custom: ['https://www.buymeacoffee.com/theraloss'] 3 | -------------------------------------------------------------------------------- /src/Exceptions/InvalidTokenException.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ./tests 6 | 7 | 8 | 9 | 10 | ./src 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /tests/Pest.php: -------------------------------------------------------------------------------- 1 | in(__DIR__); 15 | -------------------------------------------------------------------------------- /src/Helpers/RoleManager.php: -------------------------------------------------------------------------------- 1 | user())->roles ?: []; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /tests/Helpers/RoleManagerTest.php: -------------------------------------------------------------------------------- 1 | toBe([]); 9 | }); 10 | 11 | test('::getRoles() with a logged in user', function () { 12 | Auth::guard('fusionauth')->setUser( 13 | new FusionAuthJwtUser(['roles' => ['user', 'admin']]) 14 | ); 15 | 16 | expect(RoleManager::getRoles())->toBe(['user', 'admin']); 17 | }); 18 | 19 | test('::hasRole() false when not logged in', function () { 20 | expect(RoleManager::hasRole('user'))->toBeFalse(); 21 | }); 22 | 23 | test('::hasRole() with a logged in user', function () { 24 | Auth::guard('fusionauth')->setUser( 25 | new FusionAuthJwtUser(['roles' => ['user', 'admin']]) 26 | ); 27 | 28 | expect(RoleManager::hasRole('user'))->toBeTrue(); 29 | expect(RoleManager::hasRole('foobar'))->toBeFalse(); 30 | }); 31 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Danilo Polani 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | set('auth.guards.fusionauth', [ 34 | 'driver' => 'fusionauth', 35 | 'provider' => 'fusionauth', 36 | ]); 37 | $app['config']->set('auth.providers.fusionauth', [ 38 | 'driver' => 'fusionauth', 39 | ]); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Http/Middleware/CheckRole.php: -------------------------------------------------------------------------------- 1 | check()) { 26 | throw new UnauthorizedHttpException('Bearer'); 27 | } 28 | 29 | $finalRole = $role ?: Config::get('fusionauth.default_role'); 30 | 31 | if (is_null($finalRole) || !RoleManager::hasRole($finalRole)) { 32 | throw new UnauthorizedHttpException('Bearer role="' . $role . '"'); 33 | } 34 | 35 | return $next($request); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: run-tests 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | fail-fast: true 10 | matrix: 11 | php: [8.4, 8.3, 8.2] 12 | laravel: ["^12.0", "^11.0", "^10.0"] 13 | include: 14 | - laravel: "^12.0" 15 | testbench: 10.* 16 | - laravel: "^11.0" 17 | testbench: 9.* 18 | - laravel: "^10.0" 19 | testbench: 8.* 20 | 21 | name: PHP ${{ matrix.php }} - Laravel ${{ matrix.laravel }} 22 | 23 | steps: 24 | - name: Checkout code 25 | uses: actions/checkout@v4 26 | 27 | - name: Setup PHP 28 | uses: shivammathur/setup-php@v2 29 | with: 30 | php-version: ${{ matrix.php }} 31 | extensions: dom, curl, libxml, mbstring, zip 32 | coverage: none 33 | 34 | - name: Setup problem matchers 35 | run: | 36 | echo "::add-matcher::${{ runner.tool_cache }}/php.json" 37 | echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" 38 | - name: Install dependencies 39 | run: | 40 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update 41 | composer update --prefer-dist --no-interaction 42 | - name: Execute tests 43 | run: vendor/bin/pest 44 | -------------------------------------------------------------------------------- /src/FusionAuthJwtUserProvider.php: -------------------------------------------------------------------------------- 1 | mergeConfigFrom(__DIR__.'/../config/fusionauth.php', 'fusionauth'); 19 | } 20 | 21 | public function boot() 22 | { 23 | Auth::provider( 24 | 'fusionauth', 25 | fn (Application $app) => $app->make(FusionAuthJwtUserProvider::class) 26 | ); 27 | 28 | Auth::extend( 29 | 'fusionauth', 30 | fn (Application $app, string $name, array $config) => new RequestGuard( 31 | fn (Request $request, FusionAuthJwtUserProvider $provider) => $provider->retrieveByCredentials([ 32 | 'jwt' => $request->bearerToken(), 33 | ]), 34 | $app['request'], 35 | $app['auth']->createUserProvider($config['provider']) 36 | ) 37 | ); 38 | 39 | /** @var Router $router */ 40 | $router = $this->app->make(Router::class); 41 | $router->aliasMiddleware('fusionauth.role', CheckRole::class); 42 | 43 | if ($this->app->runningInConsole()) { 44 | $this->publishes([ 45 | __DIR__.'/../config/fusionauth.php' => config_path('fusionauth.php'), 46 | ], 'fusionauth-jwt-config'); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "danilopolani/laravel-fusionauth-jwt", 3 | "description": "Laravel Auth guard for FusionAuth JWT", 4 | "keywords": [ 5 | "danilopolani", 6 | "laravel-fusionauth-jwt" 7 | ], 8 | "homepage": "https://github.com/danilopolani/laravel-fusionauth-jwt", 9 | "license": "MIT", 10 | "type": "library", 11 | "authors": [ 12 | { 13 | "name": "Danilo Polani", 14 | "email": "danilo.polani@gmail.com", 15 | "role": "Developer" 16 | } 17 | ], 18 | "require": { 19 | "php": "^8.2", 20 | "firebase/php-jwt": "^6.4", 21 | "illuminate/auth": "^10.0|^11.0|^12.0", 22 | "illuminate/http": "^10.0|^11.0|^12.0", 23 | "illuminate/contracts": "^10.0|^11.0|^12.0", 24 | "illuminate/routing": "^10.0|^11.0|^12.0", 25 | "illuminate/support": "^10.0|^11.0|^12.0" 26 | }, 27 | "require-dev": { 28 | "orchestra/testbench": "^8.0|^9.0|^10.0", 29 | "pestphp/pest": "^2.0|^3.0" 30 | }, 31 | "autoload": { 32 | "psr-4": { 33 | "DaniloPolani\\FusionAuthJwt\\": "src" 34 | } 35 | }, 36 | "autoload-dev": { 37 | "psr-4": { 38 | "DaniloPolani\\FusionAuthJwt\\Tests\\": "tests" 39 | } 40 | }, 41 | "scripts": { 42 | "test": "vendor/bin/pest" 43 | }, 44 | "config": { 45 | "sort-packages": true, 46 | "allow-plugins": { 47 | "pestphp/pest-plugin": true 48 | } 49 | }, 50 | "extra": { 51 | "laravel": { 52 | "providers": [ 53 | "DaniloPolani\\FusionAuthJwt\\FusionAuthJwtServiceProvider" 54 | ] 55 | } 56 | }, 57 | "minimum-stability": "dev", 58 | "prefer-stable": true 59 | } 60 | -------------------------------------------------------------------------------- /tests/FusionAuthJwtTest.php: -------------------------------------------------------------------------------- 1 | throws(InvalidTokenAlgorithmException::class); 13 | 14 | test('::validate() will throw an error if the issuer is not authorized', function () { 15 | Config::set('fusionauth.audience', 'bar'); 16 | Config::set('fusionauth.issuers', ['foo', 'bar']); 17 | 18 | FusionAuthJwt::validate((object) ['aud' => 'bar', 'iss' => 'baz']); 19 | })->throws(InvalidTokenException::class); 20 | 21 | test('::validate() will throw an error if the audience or client_id are not authorized', function () { 22 | Config::set('fusionauth.client_id', 'foo'); 23 | Config::set('fusionauth.audience', 'bar'); 24 | Config::set('fusionauth.issuers', ['foo', 'bar']); 25 | 26 | FusionAuthJwt::validate((object) ['aud' => 'baz', 'iss' => 'bar']); 27 | })->throws(InvalidTokenException::class); 28 | 29 | test('::validate() will not throw anything if everything is good', function () { 30 | Config::set('fusionauth.audience', 'bar'); 31 | Config::set('fusionauth.issuers', ['foo', 'bar']); 32 | 33 | FusionAuthJwt::validate((object) ['aud' => 'bar', 'iss' => 'foo']); 34 | 35 | // Basic expectation to avoid the warning 36 | expect(true)->toBeTrue(); 37 | }); 38 | 39 | test('::validate() will not throw anything if audience matches the client_id', function () { 40 | Config::set('fusionauth.client_id', 'baz'); 41 | Config::set('fusionauth.audience', 'foo'); 42 | Config::set('fusionauth.issuers', ['foo', 'bar']); 43 | 44 | FusionAuthJwt::validate((object) ['aud' => 'baz', 'iss' => 'foo']); 45 | 46 | // Basic expectation to avoid the warning 47 | expect(true)->toBeTrue(); 48 | }); 49 | -------------------------------------------------------------------------------- /tests/ Middleware/CheckRoleTest.php: -------------------------------------------------------------------------------- 1 | request = new Request(); 16 | $this->nullFn = fn () => assertTrue(true); 17 | }); 18 | 19 | test('block if guest', function () { 20 | (new CheckRole())->handle($this->request, $this->nullFn); 21 | })->throws(UnauthorizedHttpException::class); 22 | 23 | test('block if no role specified', function () { 24 | Auth::guard('fusionauth')->setUser(new FusionAuthJwtUser([])); 25 | 26 | (new CheckRole())->handle($this->request, $this->nullFn); 27 | })->throws(UnauthorizedHttpException::class); 28 | 29 | test('block if user has not the default role', function () { 30 | Auth::guard('fusionauth')->setUser( 31 | new FusionAuthJwtUser(['roles' => ['foo']]) 32 | ); 33 | 34 | (new CheckRole())->handle($this->request, $this->nullFn); 35 | })->throws(UnauthorizedHttpException::class); 36 | 37 | test('block if user has not the custom role provided', function () { 38 | Auth::guard('fusionauth')->setUser( 39 | new FusionAuthJwtUser(['roles' => ['user']]) 40 | ); 41 | 42 | (new CheckRole())->handle($this->request, $this->nullFn, 'admin'); 43 | })->throws(UnauthorizedHttpException::class); 44 | 45 | test('handles default role for a user', function () { 46 | Auth::guard('fusionauth')->setUser( 47 | new FusionAuthJwtUser(['roles' => ['user']]) 48 | ); 49 | 50 | (new CheckRole())->handle($this->request, $this->nullFn); 51 | }); 52 | 53 | test('handles a custom role', function () { 54 | Auth::guard('fusionauth')->setUser( 55 | new FusionAuthJwtUser(['roles' => ['user', 'admin']]) 56 | ); 57 | 58 | (new CheckRole())->handle($this->request, $this->nullFn, 'admin'); 59 | }); 60 | -------------------------------------------------------------------------------- /config/fusionauth.php: -------------------------------------------------------------------------------- 1 | env('FUSIONAUTH_DOMAIN'), 12 | 13 | /* 14 | |-------------------------------------------------------------------------- 15 | | App Client ID 16 | |-------------------------------------------------------------------------- 17 | | 18 | */ 19 | 'client_id' => env('FUSIONAUTH_CLIENT_ID'), 20 | 21 | /* 22 | |-------------------------------------------------------------------------- 23 | | App Client Secret 24 | |-------------------------------------------------------------------------- 25 | | 26 | */ 27 | 'client_secret' => env('FUSIONAUTH_CLIENT_SECRET'), 28 | 29 | /* 30 | |-------------------------------------------------------------------------- 31 | | Authorized issuers 32 | |-------------------------------------------------------------------------- 33 | | 34 | */ 35 | 'issuers' => [ 36 | env('FUSIONAUTH_ISSUER'), 37 | ], 38 | 39 | /* 40 | |-------------------------------------------------------------------------- 41 | | Authorized audience 42 | |-------------------------------------------------------------------------- 43 | | 44 | */ 45 | 'audience' => [ 46 | env('FUSIONAUTH_AUDIENCE'), 47 | ], 48 | 49 | /* 50 | |-------------------------------------------------------------------------- 51 | | Token supported algorithms 52 | |-------------------------------------------------------------------------- 53 | | 54 | */ 55 | 'supported_algs' => ['RS256'], 56 | 57 | /* 58 | |-------------------------------------------------------------------------- 59 | | Default role name 60 | |-------------------------------------------------------------------------- 61 | | 62 | | Name of the default role to check when using the CheckRole middleware. 63 | | 64 | */ 65 | 'default_role' => null, 66 | ]; 67 | -------------------------------------------------------------------------------- /src/FusionAuthJwtUser.php: -------------------------------------------------------------------------------- 1 | $roles 18 | * @property-read int $exp 19 | * @property-read int $iat 20 | */ 21 | class FusionAuthJwtUser implements Authenticatable 22 | { 23 | private array $userInfo; 24 | 25 | /** 26 | * FusionAuthUser constructor. 27 | * 28 | * @param array $userInfo 29 | */ 30 | public function __construct(array $userInfo) 31 | { 32 | $this->userInfo = $userInfo; 33 | } 34 | 35 | /** 36 | * {@inheritDoc} 37 | */ 38 | public function getAuthIdentifierName() 39 | { 40 | return $this->userInfo['sub']; 41 | } 42 | 43 | /** 44 | * {@inheritDoc} 45 | */ 46 | public function getAuthIdentifier() 47 | { 48 | return $this->userInfo['sub']; 49 | } 50 | 51 | /** 52 | * {@inheritDoc} 53 | */ 54 | public function getAuthPassword() 55 | { 56 | return ''; 57 | } 58 | 59 | /** 60 | * {@inheritDoc} 61 | */ 62 | public function getAuthPasswordName() 63 | { 64 | return ''; 65 | } 66 | 67 | /** 68 | * {@inheritDoc} 69 | */ 70 | public function getRememberToken() 71 | { 72 | return ''; 73 | } 74 | 75 | /** 76 | * {@inheritDoc} 77 | */ 78 | public function setRememberToken($value) 79 | { 80 | // 81 | } 82 | 83 | /** 84 | * {@inheritDoc} 85 | */ 86 | public function getRememberTokenName() 87 | { 88 | return ''; 89 | } 90 | 91 | /** 92 | * Get the whole user info array. 93 | * 94 | * @return array 95 | */ 96 | public function getUserInfo(): array 97 | { 98 | return $this->userInfo; 99 | } 100 | 101 | /** 102 | * Add a generic getter to get all the properties of the userInfo. 103 | * 104 | * @param string $name 105 | * @return mixed the related value or null if not found 106 | */ 107 | public function __get($name) 108 | { 109 | return $this->userInfo[$name] ?? null; 110 | } 111 | 112 | /** 113 | * Stringify the current user. 114 | * 115 | * @return string 116 | */ 117 | public function __toString() 118 | { 119 | return json_encode($this->userInfo); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /src/FusionAuthJwt.php: -------------------------------------------------------------------------------- 1 | iss, Config::get('fusionauth.issuers'))) { 73 | throw new InvalidTokenException('Issuer "' . $token->iss . '" is not authorized.'); 74 | } 75 | 76 | $possibleAudiences = [ 77 | // Fallback to client_id to avoid "null $token->aud" matching "null fusionauth.audience" 78 | ...Arr::wrap(Config::get('fusionauth.audience', Config::get('fusionauth.client_id'))), 79 | Config::get('fusionauth.client_id'), 80 | ]; 81 | 82 | // Validate aud against the audience and client id (may be a token from client_credentials) 83 | if (!in_array($token->aud, $possibleAudiences)) { 84 | throw new InvalidTokenException('Audience "' . $token->aud . '" is not authorized.'); 85 | } 86 | } 87 | 88 | /** 89 | * Fetch public keys generated from JWKS. 90 | * 91 | * @return array 92 | */ 93 | protected static function fetchPublicKeys(string $algorithm): array 94 | { 95 | return Cache::remember( 96 | 'fusionauth.v2.public_keys', 97 | self::JWKS_CACHE_TTL, 98 | fn () => Http::get('https://' . Config::get('fusionauth.domain') . '/api/jwt/public-key') 99 | ->throw() 100 | ->collect('publicKeys', []) 101 | ->map(fn (string $key) => new Key($key, $algorithm)) 102 | ->toArray() 103 | ); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel FusionAuth JWT 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/danilopolani/laravel-fusionauth-jwt.svg?style=flat-square)](https://packagist.org/packages/danilopolani/laravel-fusionauth-jwt) 4 | [![Total Downloads](https://img.shields.io/packagist/dt/danilopolani/laravel-fusionauth-jwt.svg?style=flat-square)](https://packagist.org/packages/danilopolani/laravel-fusionauth-jwt) 5 | ![GitHub Actions](https://github.com/danilopolani/laravel-fusionauth-jwt/actions/workflows/main.yml/badge.svg) 6 | 7 | Implement an Auth guard for FusionAuth JWTs in Laravel. 8 | It ships with also a middleware to check against the user role. 9 | 10 | ## Installation 11 | 12 | You can install the package via composer: 13 | 14 | ```bash 15 | composer require danilopolani/laravel-fusionauth-jwt 16 | ``` 17 | 18 | Then publish its config file: 19 | 20 | ```bash 21 | php artisan vendor:publish --tag=fusionauth-jwt-config 22 | ``` 23 | 24 | ## Configuration 25 | 26 | There are a few notable configuration options for the package. 27 | 28 | Key | Type | Description 29 | ------------ | ------------- | ------------- 30 | `domain` | String | Your FusionAuth domain, e.g. `auth.myapp.com` or `sandbox.fusionauth.io`. 31 | `client_id` | String | The Client ID of the current application. 32 | `client_secret` | String | The Client Secret of the current application. 33 | `issuers` | Array | A list of authorized issuers for the incoming JWT. 34 | `audience` | String \| Null | The ID/Name of the authorized audience. If null, the **Client ID** will be used. 35 | `supported_algs` | Array | The supported algorithms of the JWT. Supported: `RS256` and `HS256`. 36 | `default_role` | String \| Null | The default role to be checked if you're using the [`CheckRole`](#role-middleware) middleware. 37 | 38 | ## Usage 39 | 40 | To start protecting your APIs you need to add the Guard and the Auth Provider to your `config/auth.php` configuration file: 41 | 42 | ```php 43 | 'guards' => [ 44 | // ... 45 | 'fusionauth' => [ 46 | 'driver' => 'fusionauth', 47 | 'provider' => 'fusionauth', 48 | ], 49 | ], 50 | 51 | 'providers' => [ 52 | // ... 53 | 'fusionauth' => [ 54 | 'driver' => 'fusionauth', 55 | ], 56 | ], 57 | ``` 58 | 59 | Then you can use the `auth:fusionauth` guard to protect your endpoints; you can apply it to a group or a single route: 60 | 61 | ```php 62 | // app\Http\Kernel.php 63 | 64 | protected $middlewareGroups = [ 65 | 'api' => [ 66 | 'auth:fusionauth', 67 | // ... 68 | ], 69 | ]; 70 | 71 | // or routes/api.php 72 | 73 | Route::get('users', [UserController::class, 'index']) 74 | ->middleware('auth:fusionauth'); 75 | ``` 76 | 77 | Now requests for those endpoints will check if the given JWT (given as **Bearer token**) is valid. 78 | 79 | 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: 80 | 81 | ```php 82 | Auth::guard('fusionauth')->check(); 83 | 84 | /** @var \DaniloPolani\FusionAuthJwt\FusionAuthJwtUser $user */ 85 | $user = Auth::guard('fusionauth')->user(); 86 | ``` 87 | 88 | ### Role middleware 89 | 90 | The package ships with a handy middleware to check for user role (stored in the `roles` key). 91 | 92 | You can apply it on a middleware group inside the `Kernel.php` or to specific routes: 93 | 94 | ```php 95 | // app\Http\Kernel.php 96 | 97 | protected $middlewareGroups = [ 98 | 'api' => [ 99 | 'auth:fusionauth', 100 | \DaniloPolani\FusionAuthJwt\Http\Middleware\CheckRole::class, 101 | // ... 102 | ], 103 | ]; 104 | 105 | // or routes/api.php 106 | 107 | Route::get('users', [UserController::class, 'index']) 108 | ->middleware(['auth:fusionauth', 'fusionauth.role']); 109 | ``` 110 | 111 | 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: 112 | 113 | ```php 114 | // routes/api.php 115 | 116 | Route::get('users', [UserController::class, 'index']) 117 | ->middleware(['auth:fusionauth', 'fusionauth.role:admin']); 118 | ``` 119 | 120 | For more complex cases we suggest you to take a look on how the [`CheckRole`](https://github.com/danilopolani/laravel-fusionauth-jwt/blob/master/src/Http/Middleware/CheckRole.php) middleware is written (using the [`RoleManager`](https://github.com/danilopolani/laravel-fusionauth-jwt/blob/master/src/Helpers/RoleManager.php) class) and write your own. 121 | 122 | ### Usage in tests 123 | 124 | When you need to test your endpoints in Laravel, you can take advantage of the [`actingAs`](https://laravel.com/docs/8.x/http-tests#session-and-authentication) method to set the current logged in user. 125 | 126 | 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: 127 | 128 | ```php 129 | use DaniloPolani\FusionAuthJwt\FusionAuthJwtUser; 130 | 131 | $this 132 | ->actingAs( 133 | new FusionAuthJwtUser([ 134 | 'roles' => ['user', 'admin'], 135 | ]), 136 | 'fusionauth', 137 | ) 138 | ->get('/api/users') 139 | ->assertOk(); 140 | ``` 141 | 142 | 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: 143 | 144 | ```php 145 | use DaniloPolani\FusionAuthJwt\FusionAuthJwtUser; 146 | use Illuminate\Support\Facades\Auth; 147 | 148 | Auth::guard('fusionauth')->setUser( 149 | new FusionAuthJwtUser([ 150 | 'roles' => ['user', 'admin'], 151 | ]) 152 | ); 153 | ``` 154 | 155 | ### Changelog 156 | 157 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 158 | 159 | ## Contributing 160 | 161 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 162 | 163 | ### Security 164 | 165 | If you discover any security related issues, please email danilo.polani@gmail.com instead of using the issue tracker. 166 | 167 | ## Credits 168 | 169 | - [Danilo Polani](https://github.com/danilopolani) 170 | - [All Contributors](../../contributors) 171 | 172 | ## License 173 | 174 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 175 | 176 | ## Laravel Package Boilerplate 177 | 178 | This package was generated using the [Laravel Package Boilerplate](https://laravelpackageboilerplate.com). 179 | --------------------------------------------------------------------------------