|
| 1 | +# Password grant handling |
| 2 | + |
| 3 | +The `password` grant issues access and refresh tokens that are bound to both a client and a user within your application. As user system implementations can differ greatly on an application basis, the `league.oauth2_server.event.user_resolve` was created which allows you to decide which user you want to bind to issuing tokens. |
| 4 | + |
| 5 | +## Requirements |
| 6 | + |
| 7 | +The user model should implement the `Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface` interface. |
| 8 | + |
| 9 | +## Example |
| 10 | + |
| 11 | +### Listener |
| 12 | + |
| 13 | +```php |
| 14 | +<?php |
| 15 | + |
| 16 | +namespace App\EventListener; |
| 17 | + |
| 18 | +use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; |
| 19 | +use Symfony\Component\Security\Core\User\UserProviderInterface; |
| 20 | +use Symfony\Component\Security\Core\Exception\AuthenticationException; |
| 21 | +use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface; |
| 22 | +use League\Bundle\OAuth2ServerBundle\Event\UserResolveEvent; |
| 23 | + |
| 24 | +final class UserResolveListener |
| 25 | +{ |
| 26 | + /** |
| 27 | + * @var UserProviderInterface |
| 28 | + */ |
| 29 | + private $userProvider; |
| 30 | + |
| 31 | + /** |
| 32 | + * @var UserPasswordHasherInterface |
| 33 | + */ |
| 34 | + private $userPasswordHasher; |
| 35 | + |
| 36 | + public function __construct(UserProviderInterface $userProvider, UserPasswordHasherInterface $userPasswordHasher) |
| 37 | + { |
| 38 | + $this->userProvider = $userProvider; |
| 39 | + $this->userPasswordHasher = $userPasswordHasher; |
| 40 | + } |
| 41 | + |
| 42 | + public function onUserResolve(UserResolveEvent $event): void |
| 43 | + { |
| 44 | + try { |
| 45 | + $user = $this->userProvider->loadUserByIdentifier($event->getUsername()); |
| 46 | + } catch (AuthenticationException $e) { |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + if (null === $user || !($user instanceof PasswordAuthenticatedUserInterface)) { |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + if (!$this->userPasswordHasher->isPasswordValid($user, $event->getPassword())) { |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + $event->setUser($user); |
| 59 | + } |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | +### Service configuration |
| 64 | + |
| 65 | +```yaml |
| 66 | +App\EventListener\UserResolveListener: |
| 67 | + arguments: |
| 68 | + - '@security.user_providers' |
| 69 | + - '@security.password_hasher' |
| 70 | + tags: |
| 71 | + - { name: kernel.event_listener, event: league.oauth2_server.event.user_resolve, method: onUserResolve } |
| 72 | +``` |
0 commit comments