0
votes

I want to login on the homepage instead of separate site. When I type my credentials in /login route, everything is okay, but it does not work on the / route.

I render login form with this command in base.html.twig (for testing purposes I want to render login form at each page now):

{{ render(controller("AppBundle:Security:login")) }}

Here is my login.html.twig:

    {% if error %}
        <div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
    {% endif %}

    <form action="{{ path('login') }}" method="post">
        <div class="form-group">
            <input type="text" class="form-control" id="username" placeholder="Email" name="_username" value="{{ last_username }}" />

            <input type="password" class="form-control" id="password" placeholder="Heslo" name="_password" />
        </div>
        <button type="submit" class="btn btn-success">Přihlásit</button>
        <a href="/registration" class="btn btn-info" role="button">Registrovat</a>
    </form>

And my loginAction:

   /**
     * @return array
     * @Route("/login", name="login")
     * @Template()
     */
    public function loginAction()
    {
        $authenticationUtils = $this->get('security.authentication_utils');

        // get error
        $error = $authenticationUtils->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return [
            'last_username' => $lastUsername,
            'error'         => $error
        ];
    }

And secured_area in security.yml:

    secured_area:
            pattern: ^/
            anonymous: ~
            provider: main
            form_login:
                login_path: login
                check_path: login
            logout:
                path: /logout
                target: /

The login form successfully renders at homepage. But nothing happen when I enter the credentials and click the button. Maybe because the button tries to find a form in action defined for homepage instead of action defined for login page?

Is there an option to "force" the button to use original (login) action instead?

Thank you for your answers.

1

1 Answers

1
votes

You should post the login form to the check_path configured in your security.yml, not to the controller displaying your login form.

It is this URL (which is intercepted entirely by the security extension) that will authenticate the user, and if an error occurs, will redirect the user back to the login action.

For detailed instructions on how to set-up form based login, check the dedicated cookbook article in the documentation: http://symfony.com/doc/current/cookbook/security/form_login_setup.html