Symfony 3 - 自定义用户提供程序 - 登录始终显示"bad credentials"而不是"username not found"



我正在Symfony 3中开发我的第一个项目。我实现了Symfony文档中描述的自定义用户提供商。登录工作非常完美,但是当我输入不存在的用户时,我总是会收到错误消息"不良凭据"。我很想展示在用户纳米诺特(Usernamenotfound)中声明的信息,但它不起作用。如果我在安全性中添加" hide_user_not_found:false"。我还想实现CustomuserSermessageAuthenticationException,但这就是问题的第二部分。希望有人可以帮助我!这是代码...谢谢!!!

代码与这里完全相同:http://symfony.com/doc/current/security/custom_provider.html

文件:src/appbundle/security/user/weberviceuser.php

namespace AppBundleSecurityUser;
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;
    }
}

文件:src/appbundle/security/user/weberviceuserprovider.php

namespace AppBundleSecurityUser;
use AppBundleSecurityUserWebserviceUser;
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 WebserviceUser::class === $class;
    }
}

文件:src appbundle controller securityController.php

namespace AppBundleController;

use AppBundleControllerBaseController;
use SymfonyComponentHttpFoundationRequest;
use SensioBundleFrameworkExtraBundleConfigurationRoute;
use AppBundleSecurityUserWebserviceUser;

class SecurityController extends BaseController
{
    /**
     * @Route("/login", name="login")
     */
        public function loginAction(Request $request)
    {
        $authenticationUtils = $this->get('security.authentication_utils');

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();
        return $this->render('security/login.html.twig', array(
            'last_username' => $lastUsername,
            'error'         => $error
        ));
    }

}

文件:app resources views security security login.html.twig

{% extends 'base.html.twig' %}
{% block body %}

    <div class="wrapper fullscreen">
        <div class="image_full">
        </div>
        <div class="small_content">
            <a href="" class="logo_small"></a>



            <form action="{{ path('login') }}" method="post">
                {% if error %}
                    <p class="text-danger text-center">{{ error.messageKey|trans(error.messageData, 'security') }}</p>
                {% endif %}
                <div class="form-group">
                    <label for="exampleInputEmail1">Email-Adresse</label>
                    <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" name="_username" value="{{ last_username }}">
                </div>
                <div class="form-group">
                    <label for="exampleInputPassword1">Passwort</label>
                    <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Passwort" name="_password">
                </div>
                <div class="col-md-6 left">
                    <button type="submit" class="btn btn-default green btn_full">Anmelden</button>
                    <!--<a class="btn btn-default green btn_full" href="">Anmelden</a>-->
                </div>
                <div class="col-md-6 right">
                    <a class="btn btn-default green btn_full" href="{{ path('register') }}">Registrieren</a>
                </div>
                <!--<button type="submit" class="btn btn-default green btn_full">Einloggen</button>-->
            </form>
        </div>
    </div>

{% endblock %}

文件:app config security.yml

# To get started with security, check out the documentation:
# http://symfony.com/doc/current/book/security.html
security:
    # http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
    providers:
        #in_memory:
            #memory: ~
        webservice:
                    id: app.webservice_user_provider
    hide_user_not_found:  false
    #erase_credentials:    true
    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        #dev:
           # pattern: ^/(_(profiler|wdt)|css|images|js)/
           # security: false
        main:
            anonymous: ~
            form_login:
                login_path: login
                check_path: login
            logout:
                path:   /logout
                target: /
            # activate different ways to authenticate
            # http_basic: ~
            # http://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate
            # form_login: ~
            # http://symfony.com/doc/current/cookbook/security/form_login_setup.html
    encoders:
            AppBundleSecurityUserWebserviceUser: plaintext

我知道更改该Bad credentials.错误消息的两种方法:

1)

# AppBundle/Resources/translations/messages.en.yml:
# or you can put this in app/Resources/translations/message.en.yml - has the same effect
"Bad credentials.": "Your custom error message here."
# app/Resources/Security/login.html.twig
...
{% if error %}
    <div class="error">{{ error.message|trans }}</div>
{% endif %}
# app/config/config.yml, where %locale%, in this case, is set to "en"
framework:
    translator: { fallback: "%locale%" }

2)

# login.html.twig
{% if error %}
    <div>
    {{ error.message|replace({"Bad credentials.":"Your custom error message here."}) }}
    </div>
{% endif %}

您可以尝试以下两者之一,看看哪个适合您的需求。

最新更新