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

发布于 2015-08-27 16:44:40 | 172 次阅读 | 评论: 0 | 来源: 网络整理

2.6 新版功能: The TokenStorageInterface was introduced in Symfony 2.6. Prior, you had to use the getToken() method of the SecurityContextInterface.

When a request points to a secured area, and one of the listeners from the firewall map is able to extract the user’s credentials from the current Request object, it should create a token, containing these credentials. The next thing the listener should do is ask the authentication manager to validate the given token, and return an authenticated token if the supplied credentials were found to be valid. The listener should then store the authenticated token using the token storage:

use SymfonyComponentSecurityHttpFirewallListenerInterface;
use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorageInterface;
use SymfonyComponentSecurityCoreAuthenticationAuthenticationManagerInterface;
use SymfonyComponentHttpKernelEventGetResponseEvent;
use SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken;

class SomeAuthenticationListener implements ListenerInterface
{
    /**
     * @var TokenStorageInterface
     */
    private $tokenStorage;

    /**
     * @var AuthenticationManagerInterface
     */
    private $authenticationManager;

    /**
     * @var string Uniquely identifies the secured area
     */
    private $providerKey;

    // ...

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

        $username = ...;
        $password = ...;

        $unauthenticatedToken = new UsernamePasswordToken(
            $username,
            $password,
            $this->providerKey
        );

        $authenticatedToken = $this
            ->authenticationManager
            ->authenticate($unauthenticatedToken);

        $this->tokenStorage->setToken($authenticatedToken);
    }
}

注解

A token can be of any class, as long as it implements TokenInterface.

The Authentication Manager

The default authentication manager is an instance of AuthenticationProviderManager:

use SymfonyComponentSecurityCoreAuthenticationAuthenticationProviderManager;

// instances of SymfonyComponentSecurityCoreAuthenticationAuthenticationProviderInterface
$providers = array(...);

$authenticationManager = new AuthenticationProviderManager($providers);

try {
    $authenticatedToken = $authenticationManager
        ->authenticate($unauthenticatedToken);
} catch (AuthenticationException $failed) {
    // authentication failed
}

The AuthenticationProviderManager, when instantiated, receives several authentication providers, each supporting a different type of token.

注解

You may of course write your own authentication manager, it only has to implement AuthenticationManagerInterface.

Authentication Providers

Each provider (since it implements AuthenticationProviderInterface) has a method supports() by which the AuthenticationProviderManager can determine if it supports the given token. If this is the case, the manager then calls the provider’s method AuthenticationProviderInterface::authenticate. This method should return an authenticated token or throw an AuthenticationException (or any other exception extending it).

Authenticating Users by their Username and Password

An authentication provider will attempt to authenticate a user based on the credentials they provided. Usually these are a username and a password. Most web applications store their user’s username and a hash of the user’s password combined with a randomly generated salt. This means that the average authentication would consist of fetching the salt and the hashed password from the user data storage, hash the password the user has just provided (e.g. using a login form) with the salt and compare both to determine if the given password is valid.

This functionality is offered by the DaoAuthenticationProvider. It fetches the user’s data from a UserProviderInterface, uses a PasswordEncoderInterface to create a hash of the password and returns an authenticated token if the password was valid:

use SymfonyComponentSecurityCoreAuthenticationProviderDaoAuthenticationProvider;
use SymfonyComponentSecurityCoreUserUserChecker;
use SymfonyComponentSecurityCoreUserInMemoryUserProvider;
use SymfonyComponentSecurityCoreEncoderEncoderFactory;

$userProvider = new InMemoryUserProvider(
    array(
        'admin' => array(
            // password is "foo"
            'password' => '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg==',
            'roles'    => array('ROLE_ADMIN'),
        ),
    )
);

// for some extra checks: is account enabled, locked, expired, etc.?
$userChecker = new UserChecker();

// an array of password encoders (see below)
$encoderFactory = new EncoderFactory(...);

$provider = new DaoAuthenticationProvider(
    $userProvider,
    $userChecker,
    'secured_area',
    $encoderFactory
);

$provider->authenticate($unauthenticatedToken);

注解

The example above demonstrates the use of the “in-memory” user provider, but you may use any user provider, as long as it implements UserProviderInterface. It is also possible to let multiple user providers try to find the user’s data, using the ChainUserProvider.

The Password Encoder Factory

The DaoAuthenticationProvider uses an encoder factory to create a password encoder for a given type of user. This allows you to use different encoding strategies for different types of users. The default EncoderFactory receives an array of encoders:

use SymfonyComponentSecurityCoreEncoderEncoderFactory;
use SymfonyComponentSecurityCoreEncoderMessageDigestPasswordEncoder;

$defaultEncoder = new MessageDigestPasswordEncoder('sha512', true, 5000);
$weakEncoder = new MessageDigestPasswordEncoder('md5', true, 1);

$encoders = array(
    'SymfonyComponentSecurityCoreUserUser' => $defaultEncoder,
    'AcmeEntityLegacyUser'                       => $weakEncoder,

    // ...
);

$encoderFactory = new EncoderFactory($encoders);

Each encoder should implement PasswordEncoderInterface or be an array with a class and an arguments key, which allows the encoder factory to construct the encoder only when it is needed.

Creating a custom Password Encoder

There are many built-in password encoders. But if you need to create your own, it just needs to follow these rules:

  1. The class must implement PasswordEncoderInterface;

  2. The implementations of encodePassword() and isPasswordValid() must first of all make sure the password is not too long, i.e. the password length is no longer than 4096 characters. This is for security reasons (see CVE-2013-5750), and you can use the isPasswordTooLong() method for this check:

    use SymfonyComponentSecurityCoreExceptionBadCredentialsException;
    
    class FoobarEncoder extends BasePasswordEncoder
    {
        public function encodePassword($raw, $salt)
        {
            if ($this->isPasswordTooLong($raw)) {
                throw new BadCredentialsException('Invalid password.');
            }
    
            // ...
        }
    
        public function isPasswordValid($encoded, $raw, $salt)
        {
            if ($this->isPasswordTooLong($raw)) {
                return false;
            }
    
            // ...
    }
    

Using Password Encoders

When the getEncoder() method of the password encoder factory is called with the user object as its first argument, it will return an encoder of type PasswordEncoderInterface which should be used to encode this user’s password:

// a AcmeEntityLegacyUser instance
$user = ...;

// the password that was submitted, e.g. when registering
$plainPassword = ...;

$encoder = $encoderFactory->getEncoder($user);

// will return $weakEncoder (see above)
$encodedPassword = $encoder->encodePassword($plainPassword, $user->getSalt());

$user->setPassword($encodedPassword);

// ... save the user

Now, when you want to check if the submitted password (e.g. when trying to log in) is correct, you can use:

// fetch the AcmeEntityLegacyUser
$user = ...;

// the submitted password, e.g. from the login form
$plainPassword = ...;

$validPassword = $encoder->isPasswordValid(
    $user->getPassword(), // the encoded password
    $plainPassword,       // the submitted password
    $user->getSalt()
);
最新网友评论  共有(0)条评论 发布评论 返回顶部

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