FOSOAuthServerBundle icon indicating copy to clipboard operation
FOSOAuthServerBundle copied to clipboard

How to associate a token with a user

Open Spomky opened this issue 14 years ago • 2 comments

In my database, all tokens have the user value set to NULL. How can I associate my tokens with the user who authorized the client ?

Spomky avatar Oct 02 '12 18:10 Spomky

Your user class must implement the User Interface.

To help you, here is my AccessToken Class using MongoDB / Doctrine ODM.

<?php

namespace Acme\AcmeBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

use FOS\OAuthServerBundle\Document\AccessToken as BaseAccessToken;
use FOS\OAuthServerBundle\Model\ClientInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
* @ODM\Document(collection="oauthAccessToken")
*/
class AccessToken extends BaseAccessToken 
{
    /**
    * @ODM\Id(strategy="auto")
    */
    protected $id;

    /**
    * @ODM\ReferenceOne(targetDocument="Acme\AcmeBundle\Document\Client", simple=true)
    */
    protected $client;

    /**
    * @ODM\ReferenceOne(targetDocument="Acme\AcmeBundle\Document\User", simple=true)
    */
    protected $user;

    public function getClient()
    {
        return $this->client;
    }

    public function setClient(ClientInterface $client)
    {
        $this->client = $client;
    }

    public function getUser()
    {
        return $this->user;
    }

    public function setUser(UserInterface $user)
    {
        $this->user = $user;
    }

}

And here is the User Document:

namespace Acme\AcmeBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Acme\AcmeBundle\Document\DocumentBase;

use Symfony\Component\Security\Core\User\UserInterface;

/**
* @ODM\Document
*/
class User extends DocumentBase implements UserInterface
{

}

Because you implements the Symfony\Component\Security\Core\User\UserInterface interface your User class needs to have the following methods defined.

public function getRoles();

public function getPassword();

public function getSalt();

public function getUsername();

public function eraseCredentials();

jmig avatar Oct 19 '12 15:10 jmig

@jmig's answer is perfect. I'm closing this issue.

willdurand avatar Nov 21 '12 02:11 willdurand