首页 > 解决方案 > 如何在 Symfony 4 中使用哈希验证匿名访问者(用户)?

问题描述

我们有一个网站,人们可以使用hash. 我们没有不同的用户。每个拥有有效哈希的人都可以登录,区分谁登录并不重要。

我已经创建了一个表单来获取控制器中的哈希值。这是简化的代码:

public function index(Request $request) {
    if ($request->isMethod('post')) {
        $token = $request->request->get('token');
        $hash = $request->request->get('hash');

        if ($this->isCsrfTokenValid('login', $token) && $this->isHashValid($hash)) {
            // redirect
        }

        // fail
    }

    return $this->render('login.html.twig', []);
}

现在$this->isHashValid()我已经可以说哈希是否有效。但我不确定,如何authenticate手动访问访问者:

isHashValid($hash) {
    // pseudo-check for the question
    if (in_array($hash, $hashes) {
        // How to authenticate the user?
        return true;
    }

    return false;
}

我还更新了security.yaml以将unauthenticated访问者重定向到已经有效的起始页:

security:
    providers:
        in_memory: { memory: ~ }
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: true

            form_login:
                login_path: '/'

    access_control:
        - { path: ^/secured, allow_if: "is_authenticated()" }

所以我的问题是,我如何在 Symfoy 4 中以编程方式对访问者进行身份验证并随后注销访问者?

User即使我们没有经典意义上的“真实用户”,我还需要创建一个-class 吗?

标签: phpsymfonyauthenticationsymfony4

解决方案


您将必须创建一个User实现UserInterface,但它可以是一个准系统类,不需要您设置任何值。只要确保getRoles()至少返回,["ROLE_USER"]其他一切都应该没问题,只返回虚拟数据或空值。

身份验证可以通过多种方式解决。

GuardAuthenticator 似乎是一个很好的解决方案:https ://symfony.com/doc/current/security/guard_authentication.html#step-2-create-the-authenticator-class

FormLoginAuthenticator 非常相似,但有些方法是基于使用登录表单自动处理的,因此实现起来更容易:https ://symfony.com/doc/current/security/form_login_setup.html

在这两种情况下,您基本上都可以这样做:getCredentials从请求中提取数据,getUser返回您的虚拟用户对象,然后checkCredentials调用您的isHashValid方法,其余部分应该是不言自明的。


推荐阅读