首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >登录FOSUserBundle后的自定义错误消息

登录FOSUserBundle后的自定义错误消息
EN

Stack Overflow用户
提问于 2018-02-28 14:17:20
回答 3查看 2.3K关注 0票数 4

我使用FOSUserBundle和Symfony 3.4登录我的用户。当他们输入错误的密码时,将显示以下消息:

我希望为用户类型添加一个检查,并添加一个自定义错误消息,例如:“您必须是一个客户才能登录。”

为了完成这个任务,我实现了一个用户检查器,但它并不像预期的那样工作:

代码语言:javascript
复制
class CustomerUserChecker implements UserCheckerInterface
{
    public function checkPreAuth(UserInterface $user)
    {
        // nothing to do here
        return;
    }

    public function checkPostAuth(UserInterface $user)
    {
        if (!$user instanceof CustomerUser) {
            throw new AuthenticationException('You must be a customer in order to login');
        }

        return;
    }
}

我得到了这个错误:

如何在文本中添加新的错误?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-02-28 14:30:44

我能够使用自定义异常实现我的目标:

代码语言:javascript
复制
<?php

namespace AppBundle\Security;

use Symfony\Component\Security\Core\Exception\AccountStatusException;

class CustomerUserException extends AccountStatusException
{
    /**
     * {@inheritdoc}
     */
    public function getMessageKey()
    {
        return 'You must be a customer in order to login.';
    }
}

用户检查器现在如下所示:

代码语言:javascript
复制
<?php

namespace AppBundle\Security;

use Application\Sonata\UserBundle\Entity\CustomerUser;
use Application\Sonata\UserBundle\Entity\User;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class CustomerUserChecker implements UserCheckerInterface
{
    public function checkPreAuth(UserInterface $user)
    {
        // nothing to do here
        return;
    }

    public function checkPostAuth(UserInterface $user)
    {
        if (!$user instanceof User) {
            return;
        }

        if (!$user instanceof CustomerUser) {
            throw new CustomerUserException();
        }
    }
}

可选,我在app/Resources/translations/security.en.xlf中创建了一个新的翻译文件

代码语言:javascript
复制
<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    <file source-language="en" datatype="plaintext" original="file.ext">
        <body>
            <trans-unit id="You must be a customer in order to login.">
                <source>You must be a customer in order to login.</source>
                <target>You must be a customer in order to login.</target>
            </trans-unit>
        </body>
    </file>
</xliff>

并且正确地显示消息:

票数 4
EN

Stack Overflow用户

发布于 2019-07-08 20:41:43

如果您抛出一个CustomUserMessageAuthenticationException而不是一个AuthenticationException,它就会工作。

票数 2
EN

Stack Overflow用户

发布于 2018-02-28 16:06:54

另一种方法是通过将validators.en.yml...vendor/friendsofsymfony/user-bundle/Resources/translations复制到...app/Resources/translations来覆盖它。在那里做任何想要的改变。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49031659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档