config/packages/security.yaml:
security:
encoders:
App\Entity\User:
algorithm: bcrypt
# ...
providers:
our_db_provider:
entity:
class: App\Entity\User
property: username
# if you're using multiple entity managers
# manager_name: customer
firewalls:
main:
anonymous: ~
form_login:
login_path: login
check_path: login
# ...
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: ROLE_ADMIN }
src/Controller/SecurityController.php:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends Controller
{
/**
* @Route("/login", name="login")
*/
public function login(Request $request, AuthenticationUtils $authenticationUtils)
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
));
}
}
src/Controller/DefaultController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class DefaultController extends Controller
{
/**
* @Route("/admin")
*/
public function admin()
{
return new Response('<html><body>Admin page!</body></html>');
}
}
templates/security/login.html.twig:
{% extends 'base.html.twig' %}
{% if error %}
<div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
<form action="{{ path('login') }}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="_username" value="{{ last_username }}" />
<label for="password">Password:</label>
<input type="password" id="password" name="_password" />
{#
If you want to control the URL the user
is redirected to on success (more details below)
<input type="hidden" name="_target_path" value="/account" />
#}
<button type="submit">login</button>
</form>
I want to load my /admin or /login page I get the error:
InvalidConfigurationException Unrecognized option "providers" under "security.encoders.App\Entity\User"
at ArrayNode->normalizeValue(array('providers' => array('our_db_provider' => array('entity' => array('class' => 'App\Entity\User', 'property' => 'email', 'firewalls' => array('main' => array('anonymous' => null, 'form_login' => array('login_path' => 'login', 'check_path' => 'login', 'access_control' => array(array('path' => '^/login', 'roles' => 'IS_AUTHENTICATED_ANONYMOUSLY'), array('path' => '^/', 'roles' => 'ROLE_ADMIN'))))))))))in BaseNode.php line 368