如何在Symfony 4中使用哈希验证匿名访问者(用户)?

We have a site where people can login using a hash. We don't have distinct users. Everyone with a valid hash can login and it's not important to distinguish who is logged in.

I already created a form to get the hash in the controller. Here's the simplified code:

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', []);
}

Now in $this->isHashValid() I can already say whether a hash is valid. But I'm not sure, how to authenticate the visitor manually:

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

    return false;
}

I also updated the security.yaml to redirect unauthenticated visitors to the startpage, which works already:

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()" }

So my question is, how can I authenticate and later log out a visitor programmatically in Symfoy 4?

Do I still need to create a User-class, even though we don't have "real users" in a classical sense?

You will have to create a User implementing the UserInterface, but it can be a barebones class that does not require you to set any values. Just make sure that getRoles() returns at least ["ROLE_USER"] and everything else should be ok to just return dummy data or null values.

The authentification can be solved multiple ways.

GuardAuthenticator seems like a good solution: https://symfony.com/doc/current/security/guard_authentication.html#step-2-create-the-authenticator-class

FormLoginAuthenticator is pretty similar, but the some methods are automatically dealt with based on using a login form, so it's a bit easier to implement: https://symfony.com/doc/current/security/form_login_setup.html

In both cases you could basically do it like this: getCredentials you extract the data from the request, in getUser you return your dummy user object and in checkCredentials you call your isHashValid method the rest should be self explanatory.