📜 ⬆️ ⬇️

Authorization for API using tokens

As promised earlier, I continue my series of articles on creating APIs on Symfony2. Today I would like to talk about authorization. Of the popular bundles, there are JWTAuthenticationBundle and FOSOAuthServerBundle, each has its own pros and cons, but I would like to tell you how to authorize yourself to understand how it works.
To begin with, let's create the UserAccessToken entity, in which we will store user access tokens.
<?php namespace App\CommonBundle\Entity; use Doctrine\ORM\Mapping AS ORM; /** * @ORM\Entity * @ORM\Table(name="user_access_tokens") */ class UserAccessToken { /** * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * @ORM\Column(name="id", type="integer") */ protected $id; /** * @ORM\ManyToOne(targetEntity="User") * @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="SET NULL") */ protected $user; /** *      .          ,     * * @ORM\Column(name="access_token", type="string") */ protected $accessToken; /** * ,        * * @ORM\Column(name="expired_at", type="datetime") */ protected $expiredAt; /** * @ORM\Column(name="created_at", type="datetime") */ protected $createdAt; } 


Now create a Listener that will listen to all requests to your API and authorize the user.

 <?php namespace App\CommonBundle\Listener; use App\CommonBundle as Common; use Doctrine\ORM\EntityManager; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\Security\Core\SecurityContextInterface; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; class AccessTokenListener { private $entityManager; private $securityContext; private $exclude = [ '/users/login', '/users/registration', ]; const EMPTY_ACCESS_TOKEN = 'empty_access_token'; const INVALID_ACCESS_TOKEN = 'invalid_access_token'; const ACCESS_TOKEN_EXPIRED = 'access_token_expired'; public function __construct(EntityManager $entityManager, SecurityContextInterface $securityContext) { $this->entityManager = $entityManager; $this->securityContext = $securityContext; } /** * @return Common\Entity\UserAccessToken */ private function getByAccessToken($accessToken) { return $this->entityManager->getRepository('CommonBundle:UserAccessToken')->findOneByAccessToken($accessToken); } public function beforeController(GetResponseEvent $event) { //        URL //    ,        if (in_array($event->getRequest()->getPathInfo(), $this->exclude)) { return; } //     X-Access-Token,    –   $accessToken = $event->getRequest()->headers->get('X-Access-Token'); if (!$accessToken) { $event->setResponse(new JsonResponse(['error' => self::EMPTY_ACCESS_TOKEN], 403)); return; } //       $token = $this->getByAccessToken($accessToken); if (!$token) { $event->setResponse(new JsonResponse(['error' => self::INVALID_ACCESS_TOKEN], 403)); return; } //       if ($token->getExpiredAt() <= new \DateTime('now')) { $event->setResponse(new JsonResponse(['error' => self::ACCESS_TOKEN_EXPIRED], 403)); return; } //  ,        $this->getUser() $user = $token->getUser(); $usernamePasswordToken = new UsernamePasswordToken($user, $user->getPassword(), "main", $user->getRoles()); $this->securityContext->setToken($usernamePasswordToken); } } 

')
And connect it to services.yml
  common.listener.access_token: class: App\CommonBundle\Listener\AccessTokenListener arguments: [@doctrine.orm.entity_manager, @security.context] tags: - { name: kernel.event_listener, event: kernel.request, method: beforeController } 


Almost everything is done, now it only remains to make a simple authorization method that will accept the login and password and, if successful, create a new UserAccessToken with the generated accessToken value and return it in the response.

Source: https://habr.com/ru/post/258903/


All Articles