【问题标题】:Authenticate users via access token in Symfony 3通过 Symfony 3 中的访问令牌对用户进行身份验证
【发布时间】:2016-04-06 06:07:18
【问题描述】:

问题


我希望通过作为 GET 参数提供给第一个请求的访问令牌对用户进行身份验证。

我从来没有在 Symfony 中实现过这样的事情,所以我按照How to Create a custom Authentication Provider 中概述的步骤进行操作,但它“不起作用”。 AuthenticationProviderInterfaceauthenticate方法没有被触发。

我尝试过的


因为主要是很多配置,我什至不知道如何调试它。这是我到目前为止得出的结论:只有AccessTokenProvider 被构造,没有别的。

代码


这些是系统的相关部分:

security.yml

security:

    # Snip default (empty) in_memory provider

    firewalls:
        # Snip dev and main (symfony default)

        accesstoken_secured:
            pattern:       ^/admin/
            accesstoken:   true

services.yml

services:
    accesstoken.security.authentication.provider:
        class: AppBundle\Security\Authentication\Provider\AccessTokenProvider
        arguments:
            - '' # User Provider
            - '%kernel.cache_dir%/security/nonces'
        public: false

    accesstoken.security.authentication.listener:
        class: AppBundle\Security\Firewall\AccessTokenListener
        arguments: ['@security.token_storage', '@security.authentication.manager']
        public: false

AccessTokenFactory

class AccessTokenFactory implements SecurityFactoryInterface
{
    public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint)
    {
        $providerId = 'security.authentication.provider.accesstoken.'.$id;
        $container
            ->setDefinition($providerId, new DefinitionDecorator('accesstoken.security.authentication.provider'))
            ->replaceArgument(0, new Reference($userProvider))
        ;

        $listenerId = 'security.authentication.listener.accesstoken.'.$id;
        $container->setDefinition($listenerId, new DefinitionDecorator('accesstoken.security.authentication.listener'));

        return array($providerId, $listenerId, $defaultEntryPoint);
    }

    public function getPosition()
    {
        return 'pre_auth';
    }

    public function getKey()
    {
        return 'accesstoken';
    }

    public function addConfiguration(NodeDefinition $node)
    {
    }
}

AccessTokenProvider

class AccessTokenProvider implements AuthenticationProviderInterface
{
    private $userProvider;

    public function __construct(UserProviderInterface $userProvider)
    {
        $this->userProvider = $userProvider;
    }

    public function authenticate(TokenInterface $token)
    {
        $user = $this->userProvider->loadUserByAccessToken($token->getAttribute('token'));

        if ($this->isTokenValid($token)) {
            $authenticatedToken = new AccessToken(['role_user']);
            $authenticatedToken->setUser($user);

            return $authenticatedToken;
        }

        throw new AuthenticationException('The WSSE authentication failed.');
    }

    protected function isTokenValid(AccessToken $token)
    {
        //TODO: Implement
        return (bool)$token->token;
    }

    public function supports(TokenInterface $token)
    {
        return $token instanceof AccessToken;
    }
}

AccessTokenListener

class AccessTokenListener
{
    protected $tokenStorage;
    protected $authenticationManager;

    /**
     * AccessTokenListener constructor.
     * @param TokenStorageInterface $tokenStorage
     * @param AuthenticationManagerInterface $authenticationManager
     */
    public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager)
    {
        $this->tokenStorage = $tokenStorage;
        $this->authenticationManager = $authenticationManager;
    }

    public function handle(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        $accesstoken = $request->get('accesstoken');

        $token = new AccessToken();
        $token->token = $accesstoken;

        try {
            $authToken = $this->authenticationManager->authenticate($token);
            $this->tokenStorage->setToken($authToken);

            return;
        } catch (AuthenticationException $failed) {
            // ... you might log something here
        }

        // By default deny authorization
        $response = new Response();
        $response->setStatusCode(Response::HTTP_FORBIDDEN);
        $event->setResponse($response);
    }
}

访问令牌

class AccessToken extends AbstractToken
{
    public $token;

    /**
     * AccessToken constructor.
     * @param array $roles
     */
    public function __construct(array $roles = array())
    {
        parent::__construct($roles);

        // If the user has roles, consider it authenticated
        $this->setAuthenticated(count($roles) > 0);
    }

    /**
     * Returns the user credentials.
     *
     * @return mixed The user credentials
     */
    public function getCredentials()
    {
        return '';
    }
}

【问题讨论】:

    标签: php authentication symfony


    【解决方案1】:

    我最终尝试以另一种方式实现它,使用How to Create a Custom Authentication System with Guard 的教程。

    这使用了 Symfony 的新 Guard 系统。它实际上很容易设置!

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 2014-02-11
      • 1970-01-01
      相关资源
      最近更新 更多