Skip to content

Instantly share code, notes, and snippets.

@cawa87
Created February 3, 2016 17:18
Show Gist options
  • Save cawa87/51f7bbfa8c64991c20f5 to your computer and use it in GitHub Desktop.
Save cawa87/51f7bbfa8c64991c20f5 to your computer and use it in GitHub Desktop.
<?php
namespace AppBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\SimplePreAuthenticatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* Аутентификация по токену
*
* Class AccessTokenAuthenticator
* @package AppBundle\Security
*/
class AccessTokenAuthenticator implements SimplePreAuthenticatorInterface
{
/**
* @var $userProvider AccessTokenProvider
*/
private $userProvider;
/**
* @param AccessTokenProvider $userProvider
*/
public function __construct(AccessTokenProvider $userProvider)
{
$this->userProvider = $userProvider;
}
/**
* Создание токена
*
* @param Request $request
* @param $providerKey
* @return PreAuthenticatedToken
*/
public function createToken(Request $request, $providerKey)
{
$accessToken = $request->query->get('access_token');
if (!$accessToken) {
throw new BadCredentialsException;
}
return new PreAuthenticatedToken('anonymous', $accessToken, $providerKey);
}
/**
* @param TokenInterface $token
* @param UserProviderInterface $userProvider
* @param $providerKey
* @return PreAuthenticatedToken
*/
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
{
$accessToken = $token->getCredentials();
$user = $this->userProvider->loadUserByAccessToken($accessToken);
if (!$user) {
throw new AuthenticationException;
}
return new PreAuthenticatedToken($user, $accessToken, $providerKey, $user->getRoles());
}
/**
* @param TokenInterface $token
* @param $providerKey
* @return bool
*/
public function supportsToken(TokenInterface $token, $providerKey)
{
return $token instanceof PreAuthenticatedToken && $providerKey === $token->getProviderKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment