Создать токен на postPersist с помощью FOSOAuthServerBundle

Я пытаюсь создать токен при регистрации. я использую FosUserBundle как аутентификатор и FOSOAuthServerBundle для API.

Все работает хорошо, когда я генерирую токен вручную. Но я хочу создать его автоматически после успешной регистрации. Итак, я создал EventListener называется TokenSetter

Вот код

class TokenSetter
{
protected $container;

public function __construct(ContainerInterface $container)
{
    $this->container = $container;
}

public function postPersist(LifecycleEventArgs $args)
{
    $user = $args->getEntity();

    if ($user instanceof Account) {
        $clientManager = $this->container->get('fos_oauth_server.client_manager.default');
        $client = $clientManager->createClient();
        $client->setRedirectUris(array('http://127.0.0.1:8000'));
        $client->setAllowedGrantTypes(array('password', 'refresh_token'));
        $clientManager->updateClient($client);

        $grantRequest = new Request(array(
            'client_id'  => $client->getPublicId(),
            'client_secret' => $client->getSecret(),
            'grant_type' => 'password',
            'username' => $user->getUsername(),
            'password' => $user->getPlainPassword()
        ));

        $tokenResponse = $this->container->get('fos_oauth_server.server')->grantAccessToken($grantRequest);

        $token = $tokenResponse->getContent();
    }
}
}

Проблема в том, что $user->getPlainPassword() возвращает пустое значение Это приводит к "invalid_request" после создания.

Есть ли способ получить простой пароль или сгенерировать токен другим способом?

1 ответ

Решение

Решил это сам.

Есть два способа решить это.

Первый способ - изменить password в client_credentials, Таким образом, вам не нужно отправлять имя пользователя и пароль при создании токена доступа. Недостатком является то, что значение user_id будет установлен в NULL,

Второе решение - создать другого слушателя. (RegistrationListener)

Вам нужно отредактировать UserEntity и добавить TempPlainPass геттер и сеттер. По сути, вам нужно сохранить обычный пароль в базе данных. onRegistrationSuccess и создайте токен с именем пользователя и паролем на onRegistrationCompleted

ВАЖНЫЙ! Не забудьте удалить TempPlainPass после генерации токена

Смотрите код ниже:

class RegistrationListener implements EventSubscriberInterface
{
protected $container;

public function __construct(ContainerInterface $container)
{
    $this->container = $container;
}


public static function getSubscribedEvents()
{
    return array(
        FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess',
        FOSUserEvents::REGISTRATION_COMPLETED => 'onRegistrationCompleted',
    );
}

public function onRegistrationSuccess(FormEvent $event)
{
    $user = $event->getForm()->getData();
    $user->setTempPlainPass($user->getPlainPassword());
    $user->setRoles(array('ROLE_ADMIN'));
}

public function onRegistrationCompleted(FilterUserResponseEvent $event)
{
    $user = $event->getUser();
    $clientManager = $this->container->get('fos_oauth_server.client_manager.default');
        $client = $clientManager->createClient();
        $client->setRedirectUris(array('http://127.0.0.1:8000'));
        $client->setAllowedGrantTypes(array('password', 'refresh_token'));
        $clientManager->updateClient($client);

        $grantRequest = new Request(array(
            'client_id'  => $client->getPublicId(),
            'client_secret' => $client->getSecret(),
            'grant_type' => 'password',
            'username' => $user->getUsername(),
            'password' => $user->getTempPlainPass()
        ));

        $this->container->get('fos_oauth_server.server')->grantAccessToken($grantRequest);

        $em = $this->container->get('doctrine.orm.default_entity_manager');
        $update = $em->getRepository(Account::class)->findOneById($user->getId());
        $update->setTempPlainPass('');
        $em->flush();
}
}
Другие вопросы по тегам