phpsymfonyuser-interfacesymfony-3.3

Authenticate User in Symfony 3 without Database


I have an application where the login process runs against an external API. The API gives me a JSON back which I store in my User Enitiy.(Call it Member)

The User Class implements AdvancedUserInterface.

And my Login Prozess.

    $firewall = 'main';
    $token = new UsernamePasswordToken($member, null, $firewall, $member->getRoles());
    $this->tokenStorage->setToken($token);
    $this->session->set('_security_'.$firewall, serialize($token));

    $request = new \Symfony\Component\HttpFoundation\Request();

    $event = new InteractiveLoginEvent($request, $token);
    $this->eventDispatcher->dispatch("security.interactive_login", $event);

But that dosen't work. Now i'm read here That this Prozess need users in a Database. My application dosen't have a User DB. Is there a way to Login the User without it.


Solution

  • You can define a custom guard authenticator: How to Create a Custom Authentication System with Guard. I will quickly go over the main steps here, but check out the link since it explains the steps in much more depth.

    First you need to create a user class and a corresponding user provider. It looks like you already have done that. You can also skip the user provider class (or create a fake one) if you don't use it in your authenticator class later.

    Next create your Authenticator class (lets say AppBundle\Security\ExternalApiAuthenticator). It is just a normal symfony service, extending Symfony\Component\Security\Guard\AbstractGuardAuthenticator. The comments on that class are pretty good at explaining how to implement it so you should check them out, but one thing that could be helpful: You can already check the credentials using your API inside the getUser method and then always return true in checkCredentials.

    Finally add some config to app/config/security.yml:

    # app/config/security.yml
    security:
        # ...
    
        firewalls:
            # ...
    
            main:
                anonymous: ~
                logout: ~
    
                guard:
                    authenticators:
                        - AppBundle\Security\ExternalApiAuthenticator