Skip to content

Commit

Permalink
Merge branch 'release/1.2.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
ollieread committed Jan 12, 2020
2 parents 512fcfb + 2204efe commit 369a152
Show file tree
Hide file tree
Showing 4 changed files with 150 additions and 7 deletions.
10 changes: 8 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [1.2.0] - 2020-01-12
### Added
- Added the `jwt:generate` command to generate keys for signing JWTs ([#7])

## [1.1.2] - 2020-01-03
### Fixed
- Fix TTL parsing when generating token ([#5])
Expand All @@ -32,9 +36,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [1.0.0] - 2019-11-19
- Initial release

[Unreleased]: https://github.com/sprocketbox/laravel-jwt/compare/v1.1.1...develop
[Unreleased]: https://github.com/sprocketbox/laravel-jwt/compare/v1.2.0...develop
[1.2.0]: https://github.com/sprocketbox/laravel-jwt/compare/v1.1.2...v1.2.0
[1.1.2]: https://github.com/sprocketbox/laravel-jwt/compare/v1.1.1...v1.1.2
[1.1.1]: https://github.com/sprocketbox/laravel-jwt/compare/v1.1.0...v1.1.1
[1.1.0]: https://github.com/sprocketbox/laravel-jwt/compare/v1.0...v1.1.0
[1.0.0]: https://github.com/sprocketbox/laravel-jwt/releases/tag/v1.0
[#5]: https://github.com/sprocketbox/laravel-jwt/pull/5
[#5]: https://github.com/sprocketbox/laravel-jwt/pull/5
[#7]: https://github.com/sprocketbox/laravel-jwt/issues/7
20 changes: 15 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ Here's an example configuration for a JWT guard.
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'key' => env('JWT_KEY'),
'key' => env('JWT_KEY_API'),
'signer' => Lcobucci\JWT\Signer\Hmac\Sha256::class,
'ttl' => 'P1M',
],
Expand All @@ -68,10 +68,9 @@ If you don't care to dive into all the extra bits you can create a very minimal
by:

- Changing the driver to `jwt`
- Adding `'key' => env('JWT_KEY'),`
- Create your key by running tinker (`php artisan tinker`) and entering `Str::random(64)`
- Copy that value and prefix with `JWT_KEY=` and add it to the end of your `.env` file.
- Make sure to add `JWT_KEY=` without the key to the `.env.example` file.
- Add `'key' => env('JWT_KEY_GUARD'),` where `GUARD` is the name of your auth guard
- Run `php artisan jwt:generate guard` where `guard` is the name of your auth guard
- Make sure to duplicate the env variable, but not the value, into your `.env.example` file

### Driver
If you wish to use the JWT driver, just set the `driver` option to `jwt`.
Expand Down Expand Up @@ -116,6 +115,17 @@ Auth::guard('api')->setTokenValidator(function (\Lcobucci\JWT\Token $token, \Spr

If the validation fails you must return `false`. Any other return type, including `null` will be treated as a pass.

## Generating keys
You can generate a key per guard by running the `jwt:generate` command with the name of the guard. The
commands signature is:

```
jwt:generate {guard}
{--length : The length of the key, defaults to 32}
{--show : Display the key instead of modifying files}
{--force : Force the operation to run when in production}
```

## Usage
This package functions in an almost identical way to Laravels session authentication, with a few exceptions.

Expand Down
122 changes: 122 additions & 0 deletions src/Commands/KeyGenerateCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
<?php

namespace Sprocketbox\JWT\Commands;

use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
use Illuminate\Support\Str;

/**
* Class KeyGenerateCommand
*
* @package Sprocketbox\JWT\Commands
*/
class KeyGenerateCommand extends Command
{
use ConfirmableTrait;

/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'jwt:generate {guard}
{--length : The length of the key, defaults to 32}
{--show : Display the key instead of modifying files}
{--force : Force the operation to run when in production}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Set the JWT key for the given guard';

/**
* @throws \Exception
*/
public function handle(): void
{
$key = $this->generateRandomKey();
$envKey = 'JWT_KEY_' . strtoupper($this->argument('guard'));

if ($this->option('show')) {
$this->line('<comment>' . $key . '</comment>');

return;
}

if (! $this->setEnvVariable($envKey, $key)) {
return;
}

$this->info('JWT key set successfully for \'' . $this->argument('guard') . '\'.');
}

/**
* Generate a random key for the JWT signing.
*
* @return string
* @throws \Exception
*/
protected function generateRandomKey(): string
{
return Str::random($this->option('length') ?: 32);
}

/**
* Set the value in the environment file.
*
* @param string $envKey
* @param string $key
*
* @return bool
*/
private function setEnvVariable(string $envKey, string $key): bool
{
$currentKey = env($envKey);

if (($currentKey !== '' || $currentKey !== null) && ! $this->confirmToProceed()) {
return false;
}

if ($currentKey !== null) {
$this->replaceKeyInEnv($envKey, $key, $currentKey);
} else {
$this->addKeyToEnv($envKey, $key);
}

return true;
}

/**
* Replace the old JWT key in the env file.
*
* @param string $envKey
* @param string $key
* @param $currentKey
*/
private function replaceKeyInEnv(string $envKey, string $key, $currentKey): void
{
file_put_contents($this->laravel->environmentFilePath(), preg_replace(
'/^' . preg_quote($envKey . '=' . $currentKey, '/') . '/m',
$envKey . '=' . $key,
file_get_contents($this->laravel->environmentFilePath())
));
}

/**
* Add the JWT key to the env file.
*
* @param string $envKey
* @param string $key
*/
private function addKeyToEnv(string $envKey, string $key): void
{
file_put_contents(
$this->laravel->environmentFilePath(),
PHP_EOL . $envKey . '=' . $key . PHP_EOL,
FILE_APPEND
);
}
}
5 changes: 5 additions & 0 deletions src/JWTServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Foundation\Application;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
use RuntimeException;
use Sprocketbox\JWT\Commands\KeyGenerateCommand;

class JWTServiceProvider extends BaseServiceProvider
{
Expand All @@ -31,5 +32,9 @@ public function register(): void

return $guard;
});

$this->commands([
KeyGenerateCommand::class,
]);
}
}

0 comments on commit 369a152

Please sign in to comment.