FOSOAuthServerBundle icon indicating copy to clipboard operation
FOSOAuthServerBundle copied to clipboard

Add custom attribute to token object

Open kbardi opened this issue 7 years ago • 1 comments

Hi there, first of all, it's a great Bundle, so thanks!!

I've just followed this doc about event dispatcher but I need to add an attribute to current token.

I've defined oauth_event_listener:

oauth_event_listener:
        class: ApiBundle\EventListener\OAuthEventListener
        tags:
            - { name: kernel.event_listener, event: fos_oauth_server.pre_authorization_process, method: onPreAuthorizationProcess }
            - { name: kernel.event_listener, event: fos_oauth_server.post_authorization_process, method: onPostAuthorizationProcess }

And I create OauthEventListener:

<?php

namespace ApiBundle\EventListener;

use FOS\OAuthServerBundle\Event\OAuthEvent;

class OAuthEventListener {
    public function onPreAuthorizationProcess(OAuthEvent $event) {
        if ($user = $this->getUser($event)) {
            $event->setAuthorizedClient(
                $user->isAuthorizedClient($event->getClient())
            );
        }
    }

    public function onPostAuthorizationProcess(OAuthEvent $event) {
        if ($event->isAuthorizedClient()) {
            if (null !== $client = $event->getClient()) {
                $user = $this->getUser($event);
                $user->addClient($client);
                $user->save();
                $token = $user->getConfirmationToken();
                $token->setAttribute('business', $user->getBusinesses()->first());
            }
        }
    }

    protected function getUser(OAuthEvent $event) {
            return UserQuery::create()
                ->filterByUsername($event->getUser()->getUsername())
                ->findOne();
    }
}

But for some reason it's not working, but it doesn't throw any error. What am I doing wrong?

Thanks in advance for any help with this.

kbardi avatar Nov 17 '17 14:11 kbardi

You're expecting it to work on every time the token is used, correct? If so, it's not supposed to work like that, the events trigger while you're acquiring the token. After that, they will not fire.

You can use events from Symfony\Component\Security\Core\AuthenticationEvents to attach listeners to the access token being used.

dkarlovi avatar Jan 11 '18 06:01 dkarlovi