Skip to content

Commit

Permalink
4.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
atlance committed Nov 28, 2023
0 parents commit 263c043
Show file tree
Hide file tree
Showing 50 changed files with 1,776 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .env.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
###> atlance/jwt-auth ###
JWT_KEY_ALGORITHM_ID=
JWT_PRIVATE_KEY_FILE=
JWT_PRIVATE_KEY_PASS_PHRASE=
JWT_PUBLIC_KEY_FILE=
JWT_CLIENT_CLAIM_NAME=client_id
JWT_TTL=3600
###< atlance/jwt-auth ###
5 changes: 5 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/.github export-ignore
/config export-ignore
/tests export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
44 changes: 44 additions & 0 deletions .github/workflows/php-analyze.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: PHP analyze & tests

on:
push: ~
pull_request: ~
schedule:
- cron: '0 */3 * * *'

permissions:
contents: read

jobs:
build:

runs-on: ubuntu-latest
strategy:
matrix:
php-version: ['7.4']

steps:
- uses: actions/checkout@master

- name: installing PHP
uses: shivammathur/setup-php@master
with:
php-version: ${{ matrix.php-version }}
tools: composer:latest

- name: Validate composer.json
run: composer validate --strict

- name: Install dependencies
run: composer install

- name: Run static php analyze.
run: composer php-analyze

- name: Run PHPUnit Tests
run: composer paratest

- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@main
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
16 changes: 16 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
!/.github
!/config
!/docs
!/src
!/tests
/tests/Kernel/var

!/.gitignore
!/.gitattributes

!/composer.json
!/*.dist

!/LICENSE.md
!/README.md
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Anton Stepanov

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.
114 changes: 114 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
Symfony 4: JWT Authentication
==============
[![composer.lock](http://poser.pugx.org/phpunit/phpunit/composerlock)](https://packagist.org/packages/phpunit/phpunit)
[![PHP analyze & tests](https://github.com/atlance/jwt-auth/actions/workflows/php-analyze.yml/badge.svg)](https://github.com/atlance/jwt-auth/actions/workflows/php-analyze.yml)
![Psalm coverage](https://shepherd.dev/github/atlance/jwt-auth/coverage.svg)
![GitHub](https://img.shields.io/badge/PHPStan-level%208-brightgreen.svg?style=flat)
[![codecov](https://codecov.io/gh/atlance/jwt-auth/graph/badge.svg?token=EV9EVMTRTL)](https://codecov.io/gh/atlance/jwt-auth)

## Installation

1. <a href="/docs/generate_keys.md" target="_blank">Generate</a> keys.
2. Install package via composer: `composer require atlance/jwt-auth ^4.0`.
3. Configure:
- Copy/paste <a href="/src/Resources/config/atlance_jwt_auth.yaml" target="_blank">configuration</a> to
`config/packages/atlance_jwt_auth.yaml`.
- Copy/paste <a href="/.env.dist" target="_blank">environments</a> to your `.env` and configure.

## Use Case

### Create:
- **Implemented:** `Atlance\JwtAuth\Security\UseCase\Create\Token\Handler`.
- **Example**:
```php
<?php

declare(strict_types=1);

namespace App\Controller\Login;

use Atlance\JwtAuth\Security\UseCase;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserProviderInterface;

/**
* @IsGranted("IS_AUTHENTICATED_ANONYMOUSLY")
* @Route("/login", name=Controller::class, methods={"POST"})
*/
final class Controller extends AbstractController
{
public function __invoke(
Request $request,
UserProviderInterface $provider,
UserPasswordEncoderInterface $encoder,
UseCase\Create\Token\HandlerInterface $handler
): JsonResponse {
/** @var array{username:string,password:string} $dataset */
$dataset = json_decode((string) $request->getContent(), true);

try {
$user = $provider->loadUserByUsername($dataset['username']);
$encoder->isPasswordValid($user, $encoder->encodePassword($user, $dataset['password']));

return new JsonResponse(['token' => $handler->handle($user)]);
} catch (UsernameNotFoundException $e) {
return new JsonResponse(null, Response::HTTP_BAD_REQUEST);
}
}
}
```

### Access:
**Implemented:** `Atlance\JwtAuth\Security\UseCase\Access\Token\Handler`.

1) Create custom [JWT Authenticator](./tests/Kernel/Infrastructure/Http/Security/Authentication/JWTAuthenticator.php).
2) Configure `security firewall`:
```yaml
# config/packages/security.yaml
security:
firewalls:
main:
guard:
authenticators:
- App\Infrastructure\Http\Security\Authentication\JWTAuthenticator
```
- **And Symfony automatically used JWT for authentication**.
- **More:** <a href="https://symfony.com/doc/4.4/security/guard_authentication.html" target="_blank">How to use
Access Token Authentication</a>.
- **Example**:
```php
<?php

declare(strict_types=1);

namespace App\Controller\Profile;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;

/**
* @IsGranted("ROLE_USER")
* @Route("/profile", name=Controller::class, methods={"GET"})
*/
final class Controller extends AbstractController
{
public function __invoke(): JsonResponse
{
return new JsonResponse(['username' => $this->getUser()->getUsername()]);
}
}
```

Resources
---------
* [component symfony/security](https://github.com/symfony/security-bundle/tree/4.4)
* [decorator of lcobucci/jwt](https://github.com/atlance/jwt-core/1.0.0)
74 changes: 74 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
{
"name": "atlance/jwt-auth",
"description": "Symfony JWT Authentication",
"license": "MIT",
"type": "symfony-bundle",
"authors": [
{
"name": "Anton Stepanov",
"email": "[email protected]"
}
],
"require": {
"php": "^7.4",
"atlance/jwt-core": "^0.1",
"symfony/security-bundle": "^4.0",
"symfony/yaml": "^4.0"
},
"require-dev": {
"ext-json": "*",
"ext-mbstring": "*",
"brianium/paratest": "^6.0",
"doctrine/annotations": "^1.0",
"ergebnis/composer-normalize": "^2.0",
"fakerphp/faker": "^1.0",
"friendsofphp/php-cs-fixer": "^3.0",
"overtrue/phplint": "^3.0",
"phpstan/extension-installer": "^1.0",
"phpstan/phpstan": "^1.0",
"phpstan/phpstan-deprecation-rules": "^1.0",
"phpstan/phpstan-phpunit": "^1.0",
"phpstan/phpstan-strict-rules": "^1.0",
"phpstan/phpstan-symfony": "^1.0",
"psalm/plugin-symfony": "^4.0",
"rector/rector": "^0.18.11",
"sensio/framework-extra-bundle": "^6.0",
"squizlabs/php_codesniffer": "^3.0",
"symfony/browser-kit": "^4.0",
"symfony/framework-bundle": "^4.0",
"symfony/validator": "^4.0",
"vimeo/psalm": "^4.0"
},
"minimum-stability": "stable",
"autoload": {
"psr-4": {
"Atlance\\JwtAuth\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Atlance\\JwtAuth\\Tests\\": "tests"
}
},
"config": {
"allow-plugins": {
"ergebnis/composer-normalize": true,
"phpstan/extension-installer": true
}
},
"scripts": {
"cs-check": "vendor/bin/php-cs-fixer fix --config config/php_cs.dist.php --dry-run",
"cs-fix": "vendor/bin/php-cs-fixer fix --config config/php_cs.dist.php",
"paratest": "XDEBUG_MODE=coverage vendor/bin/paratest -c config/phpunit.xml.dist --colors --runner=WrapperRunner --coverage-clover ./coverage.xml",
"php-analyze": [
"@psalm",
"@cs-check",
"@phplint",
"@phpstan"
],
"phplint": "vendor/bin/phplint -c config/phplint.yaml.dist",
"phpstan": "vendor/bin/phpstan analyse -c config/phpstan.neon.dist --no-progress --memory-limit=-1",
"psalm": "vendor/bin/psalm -c config/psalm.xml.dist --no-cache --threads=6 --memory-limit=-1 --shepherd",
"rector": "vendor/bin/rector process -c config/rector.dist.php"
}
}
46 changes: 46 additions & 0 deletions config/php_cs.dist.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types=1);

$curDir = dirname(__DIR__);
$finder = (new PhpCsFixer\Finder())
->in([
$curDir . '/src',
$curDir . '/tests',
])
->exclude([
'var',
])
;

return (new PhpCsFixer\Config())
->setRiskyAllowed(true)
->setCacheFile('var/phpcs-fixer.cache')
->setRules([
'@PSR12' => true,
'@Symfony' => true,
'@Symfony:risky' => true,
'linebreak_after_opening_tag' => true,
'declare_strict_types' => true,
'no_unused_imports' => true,
'no_useless_else' => true,
'no_useless_return' => true,
'mb_str_functions' => true,
'compact_nullable_typehint' => true,
'no_trailing_whitespace' => true,
'types_spaces' => ['space' => 'single'],
'array_syntax' => ['syntax' => 'short'],
'concat_space' => ['spacing' => 'one'],
'phpdoc_inline_tag_normalizer' => false,
'phpdoc_no_useless_inheritdoc' => false,
'return_type_declaration' => ['space_before' => 'none'],
'no_superfluous_phpdoc_tags' => ['allow_mixed' => true, 'allow_unused_params' => true],
'phpdoc_align' => ['align' => 'vertical'],
'ordered_class_elements' => [
'order' => [
'use_trait', 'public', 'protected', 'private', 'constant', 'constant_public', 'constant_protected', 'constant_private', 'property', 'property_static', 'property_public', 'property_protected', 'property_private', 'property_public_static', 'property_protected_static', 'property_private_static', 'construct', 'method', 'method_static', 'method_public', 'method_protected', 'method_private', 'method_public_static', 'method_protected_static', 'method_private_static', 'destruct', 'magic', 'phpunit',
],
],
])
->setFinder($finder)
;
11 changes: 11 additions & 0 deletions config/phplint.yaml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
path:
- ../src
- ../tests
jobs: 10
cache: ../var/.phplint
extensions:
- php
exclude:
- ../vendor
- ../var
- ../tests/Kernel/var
16 changes: 16 additions & 0 deletions config/phpstan.neon.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
parameters:
level: max
bootstrapFiles:
- ../vendor/autoload.php
checkMissingIterableValueType: false
checkGenericClassInNonGenericObjectType: false
tmpDir: ../var/analyze
fileExtensions:
- php
paths:
- ../src
ignoreErrors:
excludePaths:
- ../vendor
- ../var

Loading

0 comments on commit 263c043

Please sign in to comment.