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

发布于 2015-08-27 16:52:57 | 190 次阅读 | 评论: 0 | 来源: 网络整理

Part of Symfony’s standard authentication process depends on “user providers”. When a user submits a username and password, the authentication layer asks the configured user provider to return a user object for a given username. Symfony then checks whether the password of this user is correct and generates a security token so the user stays authenticated during the current session. Out of the box, Symfony has an “in_memory” and an “entity” user provider. In this entry you’ll see how you can create your own user provider, which could be useful if your users are accessed via a custom database, a file, or - as shown in this example - a web service.

Create a User Class

First, regardless of where your user data is coming from, you’ll need to create a User class that represents that data. The User can look however you want and contain any data. The only requirement is that the class implements UserInterface. The methods in this interface should therefore be defined in the custom user class: getRoles(), getPassword(), getSalt(), getUsername(), eraseCredentials(). It may also be useful to implement the EquatableInterface interface, which defines a method to check if the user is equal to the current user. This interface requires an isEqualTo() method.

This is how your WebserviceUser class looks in action:

// src/Acme/WebserviceUserBundle/Security/User/WebserviceUser.php
namespace AcmeWebserviceUserBundleSecurityUser;

use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityCoreUserEquatableInterface;

class WebserviceUser implements UserInterface, EquatableInterface
{
    private $username;
    private $password;
    private $salt;
    private $roles;

    public function __construct($username, $password, $salt, array $roles)
    {
        $this->username = $username;
        $this->password = $password;
        $this->salt = $salt;
        $this->roles = $roles;
    }

    public function getRoles()
    {
        return $this->roles;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function getSalt()
    {
        return $this->salt;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function eraseCredentials()
    {
    }

    public function isEqualTo(UserInterface $user)
    {
        if (!$user instanceof WebserviceUser) {
            return false;
        }

        if ($this->password !== $user->getPassword()) {
            return false;
        }

        if ($this->salt !== $user->getSalt()) {
            return false;
        }

        if ($this->username !== $user->getUsername()) {
            return false;
        }

        return true;
    }
}

If you have more information about your users - like a “first name” - then you can add a firstName field to hold that data.

Create a User Provider

Now that you have a User class, you’ll create a user provider, which will grab user information from some web service, create a WebserviceUser object, and populate it with data.

The user provider is just a plain PHP class that has to implement the UserProviderInterface, which requires three methods to be defined: loadUserByUsername($username), refreshUser(UserInterface $user), and supportsClass($class). For more details, see UserProviderInterface.

Here’s an example of how this might look:

// src/Acme/WebserviceUserBundle/Security/User/WebserviceUserProvider.php
namespace AcmeWebserviceUserBundleSecurityUser;

use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityCoreExceptionUsernameNotFoundException;
use SymfonyComponentSecurityCoreExceptionUnsupportedUserException;

class WebserviceUserProvider implements UserProviderInterface
{
    public function loadUserByUsername($username)
    {
        // make a call to your webservice here
        $userData = ...
        // pretend it returns an array on success, false if there is no user

        if ($userData) {
            $password = '...';

            // ...

            return new WebserviceUser($username, $password, $salt, $roles);
        }

        throw new UsernameNotFoundException(
            sprintf('Username "%s" does not exist.', $username)
        );
    }

    public function refreshUser(UserInterface $user)
    {
        if (!$user instanceof WebserviceUser) {
            throw new UnsupportedUserException(
                sprintf('Instances of "%s" are not supported.', get_class($user))
            );
        }

        return $this->loadUserByUsername($user->getUsername());
    }

    public function supportsClass($class)
    {
        return $class === 'AcmeWebserviceUserBundleSecurityUserWebserviceUser';
    }
}

Create a Service for the User Provider

Now you make the user provider available as a service:

  • YAML
    # src/Acme/WebserviceUserBundle/Resources/config/services.yml
    services:
        webservice_user_provider:
            class: AcmeWebserviceUserBundleSecurityUserWebserviceUserProvider
    
  • XML
    <!-- src/Acme/WebserviceUserBundle/Resources/config/services.xml -->
    <services>
        <service id="webservice_user_provider" class="AcmeWebserviceUserBundleSecurityUserWebserviceUserProvider" />
    </services>
    
  • PHP
    // src/Acme/WebserviceUserBundle/Resources/config/services.php
    use SymfonyComponentDependencyInjectionDefinition;
    
    $container->setDefinition(
        'webservice_user_provider',
        new Definition('AcmeWebserviceUserBundleSecurityUserWebserviceUserProvider')
    );
    

小技巧

The real implementation of the user provider will probably have some dependencies or configuration options or other services. Add these as arguments in the service definition.

注解

Make sure the services file is being imported. See 使用 imports 导入 for details.

Modify security.yml

Everything comes together in your security configuration. Add the user provider to the list of providers in the “security” section. Choose a name for the user provider (e.g. “webservice”) and mention the id of the service you just defined.

  • YAML
    # app/config/security.yml
    security:
        providers:
            webservice:
                id: webservice_user_provider
    
  • XML
    <!-- app/config/security.xml -->
    <config>
        <provider name="webservice" id="webservice_user_provider" />
    </config>
    
  • PHP
    // app/config/security.php
    $container->loadFromExtension('security', array(
        'providers' => array(
            'webservice' => array(
                'id' => 'webservice_user_provider',
            ),
        ),
    ));
    

Symfony also needs to know how to encode passwords that are supplied by website users, e.g. by filling in a login form. You can do this by adding a line to the “encoders” section in your security configuration:

  • YAML
    # app/config/security.yml
    security:
        encoders:
            AcmeWebserviceUserBundleSecurityUserWebserviceUser: sha512
    
  • XML
    <!-- app/config/security.xml -->
    <config>
        <encoder class="AcmeWebserviceUserBundleSecurityUserWebserviceUser">sha512</encoder>
    </config>
    
  • PHP
    // app/config/security.php
    $container->loadFromExtension('security', array(
        'encoders' => array(
            'AcmeWebserviceUserBundleSecurityUserWebserviceUser' => 'sha512',
        ),
    ));
    

The value here should correspond with however the passwords were originally encoded when creating your users (however those users were created). When a user submits their password, the salt value is appended to the password and then encoded using this algorithm before being compared to the hashed password returned by your getPassword() method. Additionally, depending on your options, the password may be encoded multiple times and encoded to base64.

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

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