diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..61ead86 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/vendor diff --git a/.styleci.yml b/.styleci.yml new file mode 100644 index 0000000..c3bb259 --- /dev/null +++ b/.styleci.yml @@ -0,0 +1 @@ +preset: laravel \ No newline at end of file diff --git a/changelog.md b/changelog.md new file mode 100644 index 0000000..da8d518 --- /dev/null +++ b/changelog.md @@ -0,0 +1,8 @@ +# Changelog + +All notable changes to `jwtfusionauth` will be documented in this file. + +## Version 1.0 + +### Added +- Everything diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..a21e73a --- /dev/null +++ b/composer.json @@ -0,0 +1,45 @@ +{ + "name": "werk365/jwtfusionauth", + "description": ":package_description", + "license": "MIT", + "authors": [ + { + "name": "Hergen Dillema", + "email": "h.dillema@365werk.nl", + "homepage": "https://365werk/nl" + } + ], + "homepage": "https://github.com/365werk/jwtfusionauth", + "keywords": ["Laravel", "jwtfusionauth"], + "require": { + "illuminate/support": "~5|~6|~7", + "firebase/php-jwt": "^5.2", + "phpseclib/phpseclib": "^2.0" + }, + "require-dev": { + "phpunit/phpunit": "^8.0", + "mockery/mockery": "^1.1", + "orchestra/testbench": "~3|~4", + "sempro/phpunit-pretty-print": "^1.0" + }, + "autoload": { + "psr-4": { + "werk365\\jwtfusionauth\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "werk365\\jwtfusionauth\\Tests\\": "tests" + } + }, + "extra": { + "laravel": { + "providers": [ + "werk365\\jwtfusionauth\\jwtfusionauthServiceProvider" + ], + "aliases": { + "jwtfusionauth": "werk365\\jwtfusionauth\\Facades\\jwtfusionauth" + } + } + } +} diff --git a/config/jwtfusionauth.php b/config/jwtfusionauth.php new file mode 100644 index 0000000..960bc33 --- /dev/null +++ b/config/jwtfusionauth.php @@ -0,0 +1,20 @@ + env('JWKS_URL', 'http://localhost:9011/.well-known/jwks.json'), + 'pemUri' => env('PEM_URL', 'http://localhost:9011/api/jwt/public-key'), + + // Configure to use PEM endpoint (default) or JWK + 'useJwk' => env('USE_JWK', true), + + // Column name in the users table where uuid should be stored. Defaults to id but can be another column like 'uuid' + 'userId' => env('FA_USR_ID', 'id'), + + 'autoCreateUser' => env('FA_CREATE_USR', true), + + // This uses spatie's permissions package to give users the fusionauth roles. + // To use this, installing the permissions package is required + 'usePermissions' => env('FA_USE_PERM', true), + // Creates a role if not found in database + 'autoCreateRoles' => env('FA_CREATE_ROLES', true) +]; diff --git a/contributing.md b/contributing.md new file mode 100644 index 0000000..b1e0069 --- /dev/null +++ b/contributing.md @@ -0,0 +1,27 @@ +# Contributing + +Contributions are welcome and will be fully credited. + +Contributions are accepted via Pull Requests on [Github](https://github.com/werk365/jwtfusionauth). + +# Things you could do +If you want to contribute but do not know where to start, this list provides some starting points. +- Add license text +- Remove rewriteRules.php +- Set up TravisCI, StyleCI, ScrutinizerCI +- Write a comprehensive ReadMe + +## Pull Requests + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the `readme.md` and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **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](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. + + +**Happy coding**! diff --git a/database/migrations/create_jwks_table.php.stub b/database/migrations/create_jwks_table.php.stub new file mode 100644 index 0000000..978c21b --- /dev/null +++ b/database/migrations/create_jwks_table.php.stub @@ -0,0 +1,33 @@ +id(); + $table->string('kid'); + $table->text('key'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('jwks'); + } +} diff --git a/license.md b/license.md new file mode 100644 index 0000000..9374437 --- /dev/null +++ b/license.md @@ -0,0 +1,9 @@ +# MIT + +Copyright (c) Hergen Dillema + +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. diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..ce34605 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,22 @@ + + + + + ./tests/ + + + + + src/ + + + diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..665a109 --- /dev/null +++ b/readme.md @@ -0,0 +1,57 @@ +# jwtfusionauth + +[![Latest Version on Packagist][ico-version]][link-packagist] +[![Total Downloads][ico-downloads]][link-downloads] +[![Build Status][ico-travis]][link-travis] +[![StyleCI][ico-styleci]][link-styleci] + +This is where your description should go. Take a look at [contributing.md](contributing.md) to see a to do list. + +## Installation + +Via Composer + +``` bash +$ composer require werk365/jwtfusionauth +``` + +## Usage + +## Change log + +Please see the [changelog](changelog.md) for more information on what has changed recently. + +## Testing + +``` bash +$ composer test +``` + +## Contributing + +Please see [contributing.md](contributing.md) for details and a todolist. + +## Security + +If you discover any security related issues, please email author email instead of using the issue tracker. + +## Credits + +- [author name][link-author] +- [All Contributors][link-contributors] + +## License + +license. Please see the [license file](license.md) for more information. + +[ico-version]: https://img.shields.io/packagist/v/werk365/jwtfusionauth.svg?style=flat-square +[ico-downloads]: https://img.shields.io/packagist/dt/werk365/jwtfusionauth.svg?style=flat-square +[ico-travis]: https://img.shields.io/travis/werk365/jwtfusionauth/master.svg?style=flat-square +[ico-styleci]: https://styleci.io/repos/12345678/shield + +[link-packagist]: https://packagist.org/packages/werk365/jwtfusionauth +[link-downloads]: https://packagist.org/packages/werk365/jwtfusionauth +[link-travis]: https://travis-ci.org/werk365/jwtfusionauth +[link-styleci]: https://styleci.io/repos/12345678 +[link-author]: https://github.com/werk365 +[link-contributors]: ../../contributors diff --git a/src/Facades/jwtfusionauth.php b/src/Facades/jwtfusionauth.php new file mode 100644 index 0000000..f704d7f --- /dev/null +++ b/src/Facades/jwtfusionauth.php @@ -0,0 +1,18 @@ +kid)) { + return $header->kid; + } + } + return null; + } + + private static function jwkToPem(object $jwk) + { + if (isset($jwk->e) && isset($jwk->n)) { + $rsa = new RSA(); + $rsa->loadKey([ + 'e' => new BigInteger(JWT::urlsafeB64Decode($jwk->e), 256), + 'n' => new BigInteger(JWT::urlsafeB64Decode($jwk->n), 256) + ]); + return $rsa->getPublicKey(); + } + return null; + } + + private static function getPublicKey(string $kid, string $uri) { + $jwksUrl = sprintf($uri); + $ch = curl_init($jwksUrl); + curl_setopt_array($ch, [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_TIMEOUT => 3, + ]); + $json = curl_exec($ch); + if ($json) { + $jwks = json_decode($json, false); + if ($jwks && isset($jwks->keys) && is_array($jwks->keys)) { + foreach ($jwks->keys as $jwk) { + if ($jwk->kid === $kid) { + return self::jwkToPem($jwk); + } + } + } + } + return null; + } + + private static function getPem(string $kid, string $uri) { + $pemUrl = sprintf($uri); + $ch = curl_init($pemUrl); + curl_setopt_array($ch, [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_TIMEOUT => 3, + ]); + $json = curl_exec($ch); + if ($json) { + $pems = json_decode($json, false); + if ($pems && isset($pems->publicKeys) && is_object($pems->publicKeys)) { + foreach ($pems->publicKeys as $key=>$pem) { + if ($key === $kid) { + return $pem; + } + } + } + } + return null; + } + + private static function verifyToken(string $jwt, string $uri, bool $jwk = false) + { + $publicKey = null; + $kid = self::getKid($jwt); + if ($kid) { + $row = jwk::where('kid', $kid)->orderBy('created_at', 'desc')->first(); + if (false) { + $publicKey = $row->key; + } + else { + if($jwk){ + $publicKey = self::getPublicKey($kid, $uri); + } else { + $publicKey = self::getPem($kid, $uri); + } + $row = jwk::create(['kid' => $kid, 'key' => $publicKey]); + } + } + + if ($publicKey) { + return JWT::decode($jwt, $publicKey, array('RS256')); + } + return null; + } + + public static function authUser(object $request) + { + $jwt = $request->bearerToken(); + $uri = config('jwtfusionauth.useJwk')?config('jwtfusionauth.jwkUri'):config('jwtfusionauth.pemUri'); + $claims = self::verifyToken($jwt, $uri, config('jwtfusionauth.useJwk')); + if(config('jwtfusionauth.autoCreateUser')){ + $user = User::firstOrNew([config('jwtfusionauth.userId') => $claims->sub]); + $user[config('jwtfusionauth.userId')] = $claims->sub; + $user->save(); + } else { + $user = User::where(config('jwtfusionauth.userId'), '=' , $claims->sub)->firstOrFail(); + } + if(config('jwtfusionauth.usePermissions')){ + if(config('jwtfusionauth.autoCreateRoles')){ + foreach($claims->roles as $role){ + $db_role = Role::where('name', $role)->first(); + if(!$db_role){ + Role::create(['name' => $role]); + } + } + } + $user->assignRole($claims->roles); + } + return $user; + } +} diff --git a/src/jwtfusionauthServiceProvider.php b/src/jwtfusionauthServiceProvider.php new file mode 100644 index 0000000..3eb1d1b --- /dev/null +++ b/src/jwtfusionauthServiceProvider.php @@ -0,0 +1,106 @@ +loadTranslationsFrom(__DIR__.'/../resources/lang', 'werk365'); + // $this->loadViewsFrom(__DIR__.'/../resources/views', 'werk365'); + // $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); + // $this->loadRoutesFrom(__DIR__.'/routes.php'); + + // Publishing is only necessary when using the CLI. + if ($this->app->runningInConsole()) { + $this->bootForConsole(); + } + + if (function_exists('config_path')) { // function not available and 'publish' not relevant in Lumen + $this->publishes([ + __DIR__.'/../config/jwtfusionauth.php' => config_path('jwtfusionauth.php'), + ], 'config'); + + $this->publishes([ + __DIR__.'/../database/migrations/create_jwks_table.php.stub' => $this->getMigrationFileName($filesystem), + ], 'migrations'); + } + } + + /** + * Register any package services. + * + * @return void + */ + public function register() + { + $this->mergeConfigFrom(__DIR__.'/../config/jwtfusionauth.php', 'jwtfusionauth'); + + // Register the service the package provides. + $this->app->singleton('jwtfusionauth', function ($app) { + return new jwtfusionauth; + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return ['jwtfusionauth']; + } + + /** + * Console-specific booting. + * + * @return void + */ + protected function bootForConsole() + { + // Publishing the configuration file. + $this->publishes([ + __DIR__.'/../config/jwtfusionauth.php' => config_path('jwtfusionauth.php'), + ], 'jwtfusionauth.config'); + + // Publishing the views. + /*$this->publishes([ + __DIR__.'/../resources/views' => base_path('resources/views/vendor/werk365'), + ], 'jwtfusionauth.views');*/ + + // Publishing assets. + /*$this->publishes([ + __DIR__.'/../resources/assets' => public_path('vendor/werk365'), + ], 'jwtfusionauth.views');*/ + + // Publishing the translation files. + /*$this->publishes([ + __DIR__.'/../resources/lang' => resource_path('lang/vendor/werk365'), + ], 'jwtfusionauth.views');*/ + + // Registering package commands. + // $this->commands([]); + } + + /** + * Returns existing migration file if found, else uses the current timestamp. + * + * @param Filesystem $filesystem + * @return string + */ + protected function getMigrationFileName(Filesystem $filesystem): string + { + $timestamp = date('Y_m_d_His'); + + return Collection::make($this->app->databasePath().DIRECTORY_SEPARATOR.'migrations'.DIRECTORY_SEPARATOR) + ->flatMap(function ($path) use ($filesystem) { + return $filesystem->glob($path.'*_create_jwks_tables.php'); + })->push($this->app->databasePath()."/migrations/{$timestamp}_create_permission_tables.php") + ->first(); + } +}