概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:54:30 | 179 次阅读 | 评论: 0 | 来源: 网络整理

Imagine you want to allow access to your website only between 2pm and 4pm UTC. Before Symfony 2.4, you had to create a custom token, factory, listener and provider. In this entry, you’ll learn how to do this for a login form (i.e. where your user submits their username and password). Before Symfony 2.6, you had to use the password encoder to authenticate the user password.

The Password Authenticator

2.6 新版功能: The UserPasswordEncoderInterface interface was introduced in Symfony 2.6.

First, create a new class that implements SimpleFormAuthenticatorInterface. Eventually, this will allow you to create custom logic for authenticating the user:

// src/Acme/HelloBundle/Security/TimeAuthenticator.php
namespace AcmeHelloBundleSecurity;

use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentSecurityCoreAuthenticationSimpleFormAuthenticatorInterface;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken;
use SymfonyComponentSecurityCoreEncoderUserPasswordEncoderInterface;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
use SymfonyComponentSecurityCoreExceptionUsernameNotFoundException;
use SymfonyComponentSecurityCoreUserUserProviderInterface;

class TimeAuthenticator implements SimpleFormAuthenticatorInterface
{
    private $encoder;

    public function __construct(UserPasswordEncoderInterface $encoder)
    {
        $this->encoder = $encoder;
    }

    public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {
        try {
            $user = $userProvider->loadUserByUsername($token->getUsername());
        } catch (UsernameNotFoundException $e) {
            throw new AuthenticationException('Invalid username or password');
        }

        $passwordValid = $this->encoder->isPasswordValid($user, $token->getCredentials());

        if ($passwordValid) {
            $currentHour = date('G');
            if ($currentHour < 14 || $currentHour > 16) {
                throw new AuthenticationException(
                    'You can only log in between 2 and 4!',
                    100
                );
            }

            return new UsernamePasswordToken(
                $user,
                $user->getPassword(),
                $providerKey,
                $user->getRoles()
            );
        }

        throw new AuthenticationException('Invalid username or password');
    }

    public function supportsToken(TokenInterface $token, $providerKey)
    {
        return $token instanceof UsernamePasswordToken
            && $token->getProviderKey() === $providerKey;
    }

    public function createToken(Request $request, $username, $password, $providerKey)
    {
        return new UsernamePasswordToken($username, $password, $providerKey);
    }
}

How it Works

Great! Now you just need to setup some Configuration. But first, you can find out more about what each method in this class does.

1) createToken

When Symfony begins handling a request, createToken() is called, where you create a TokenInterface object that contains whatever information you need in authenticateToken() to authenticate the user (e.g. the username and password).

Whatever token object you create here will be passed to you later in authenticateToken().

2) supportsToken

After Symfony calls createToken(), it will then call supportsToken() on your class (and any other authentication listeners) to figure out who should handle the token. This is just a way to allow several authentication mechanisms to be used for the same firewall (that way, you can for instance first try to authenticate the user via a certificate or an API key and fall back to a form login).

Mostly, you just need to make sure that this method returns true for a token that has been created by createToken(). Your logic should probably look exactly like this example.

3) authenticateToken

If supportsToken returns true, Symfony will now call authenticateToken(). Your job here is to check that the token is allowed to log in by first getting the User object via the user provider and then, by checking the password and the current time.

注解

The “flow” of how you get the User object and determine whether or not the token is valid (e.g. checking the password), may vary based on your requirements.

Ultimately, your job is to return a new token object that is “authenticated” (i.e. it has at least 1 role set on it) and which has the User object inside of it.

Inside this method, the password encoder is needed to check the password’s validity:

$passwordValid = $this->encoder->isPasswordValid($user, $token->getCredentials());

This is a service that is already available in Symfony and it uses the password algorithm that is configured in the security configuration (e.g. security.yml) under the encoders key. Below, you’ll see how to inject that into the TimeAuthenticator.

Configuration

Now, configure your TimeAuthenticator as a service:

  • YAML
    # app/config/config.yml
    services:
        # ...
    
        time_authenticator:
            class:     AcmeHelloBundleSecurityTimeAuthenticator
            arguments: ["@security.password_encoder"]
    
  • XML
    <!-- app/config/config.xml -->
    <?xml version="1.0" ?>
    <container xmlns="http://symfony.com/schema/dic/services"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/dic/services
            http://symfony.com/schema/dic/services/services-1.0.xsd">
        <services>
            <!-- ... -->
    
            <service id="time_authenticator"
                class="AcmeHelloBundleSecurityTimeAuthenticator"
            >
                <argument type="service" id="security.password_encoder" />
            </service>
        </services>
    </container>
    
  • PHP
    // app/config/config.php
    use SymfonyComponentDependencyInjectionDefinition;
    use SymfonyComponentDependencyInjectionReference;
    
    // ...
    
    $container->setDefinition('time_authenticator', new Definition(
        'AcmeHelloBundleSecurityTimeAuthenticator',
        array(new Reference('security.password_encoder'))
    ));
    

Then, activate it in the firewalls section of the security configuration using the simple_form key:

  • YAML
    # app/config/security.yml
    security:
        # ...
    
        firewalls:
            secured_area:
                pattern: ^/admin
                # ...
                simple_form:
                    authenticator: time_authenticator
                    check_path:    login_check
                    login_path:    login
    
  • XML
    <!-- app/config/security.xml -->
    <?xml version="1.0" encoding="UTF-8"?>
    <srv:container xmlns="http://symfony.com/schema/dic/security"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:srv="http://symfony.com/schema/dic/services"
        xsi:schemaLocation="http://symfony.com/schema/dic/services
            http://symfony.com/schema/dic/services/services-1.0.xsd">
        <config>
            <!-- ... -->
    
            <firewall name="secured_area"
                pattern="^/admin"
                >
                <simple-form authenticator="time_authenticator"
                    check-path="login_check"
                    login-path="login"
                />
            </firewall>
        </config>
    </srv:container>
    
  • PHP
    // app/config/security.php
    
    // ..
    
    $container->loadFromExtension('security', array(
        'firewalls' => array(
            'secured_area'    => array(
                'pattern'     => '^/admin',
                'simple_form' => array(
                    'provider'      => ...,
                    'authenticator' => 'time_authenticator',
                    'check_path'    => 'login_check',
                    'login_path'    => 'login',
                ),
            ),
        ),
    ));
    

The simple_form key has the same options as the normal form_login option, but with the additional authenticator key that points to the new service. For details, see Form Login Configuration.

If creating a login form in general is new to you or you don’t understand the check_path or login_path options, see How to Customize your Form Login.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务