Skip to content

Instantly share code, notes, and snippets.

@satujamsaja
Last active April 16, 2019 11:35
Show Gist options
  • Select an option

  • Save satujamsaja/47ca02e1e3d24f9bb66a292ec809320b to your computer and use it in GitHub Desktop.

Select an option

Save satujamsaja/47ca02e1e3d24f9bb66a292ec809320b to your computer and use it in GitHub Desktop.
Symfony 4 Guard Login Auth

Create Symfony 4 Project

  • $ composer create-project symfony/website-skeleton website

Configure database

  • Configure DATABASE_URL in .env file

Setup security

Create user class

  • $ php bin/console make:user
  • $ php bin/console make:migration
  • $ php bin/console doctrine:migrations:migrate

Create user fixtures

  • $ composer require orm-fixtures --dev
  • $ php bin/console make:fixtures
  • Create UserFixtures class. See: UserFixtures.php
  • $ php bin/console doctrine:fixtures:load

Setup auth guard

  • $ php bin/console make:auth
  • Check security.yml that include Guard
security:
encoders:
App\Entity\User:
algorithm: bcrypt
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
guard:
authenticators:
- App\Security\WebsiteLoginAuthenticator
# activate different ways to authenticate
# http_basic: true
# https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate
# form_login: true
# https://symfony.com/doc/current/security/form_login_setup.html
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
- { path: ^/profile, roles: ROLE_USER }
<?php
namespace App\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use App\Entity\User;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class UserFixtures extends Fixture
{
private $passwordEncoder;
public function __construct(UserPasswordEncoderInterface $passwordEncoder) {
$this->passwordEncoder = $passwordEncoder;
}
public function load(ObjectManager $manager)
{
$user = new User();
$user->setEmail('satujamsaja@yahoo.com');
$password = $this->passwordEncoder->encodePassword($user, 'admin');
$user->setPassword($password);
$manager->persist($user);
$manager->flush();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment