Skip to content

Instantly share code, notes, and snippets.

@sunvisor
Created March 12, 2019 23:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunvisor/9a3ac2b4ca4a35b9d45f6b3a03343c4c to your computer and use it in GitHub Desktop.
Save sunvisor/9a3ac2b4ca4a35b9d45f6b3a03343c4c to your computer and use it in GitHub Desktop.
Symfony のセキュリティ

Symfony のセキュリティ

Security の指示に従ってインストール

create-project

website-skelton

security-bundle も最初から入っている

composer create-project symfony/website-skeleton my-project

で作った場合の composer.json の require

    "require": {
        "php": "^7.1.3",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "sensio/framework-extra-bundle": "^5.2",
        "symfony/asset": "*",
        "symfony/console": "*",
        "symfony/expression-language": "*",
        "symfony/flex": "^1.1",
        "symfony/form": "*",
        "symfony/framework-bundle": "*",
        "symfony/monolog-bundle": "^3.1",
        "symfony/orm-pack": "*",
        "symfony/process": "*",
        "symfony/security-bundle": "*",
        "symfony/serializer-pack": "*",
        "symfony/swiftmailer-bundle": "^3.1",
        "symfony/translation": "*",
        "symfony/twig-bundle": "*",
        "symfony/validator": "*",
        "symfony/web-link": "*",
        "symfony/yaml": "*"
    },
    "require-dev": {
        "symfony/debug-pack": "*",
        "symfony/dotenv": "*",
        "symfony/maker-bundle": "^1.0",
        "symfony/profiler-pack": "*",
        "symfony/test-pack": "*",
        "symfony/web-server-bundle": "*"
    },

skelton

こちらはほぼ何も入っていない

composer create-project symfony/skeleton my-project
    "require": {
        "php": "^7.1.3",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "symfony/console": "*",
        "symfony/flex": "^1.1",
        "symfony/framework-bundle": "*",
        "symfony/yaml": "*"
    },
    "require-dev": {
        "symfony/dotenv": "*"
    },
composer require symfony/web-server-bundle --dev

を実行しても、require-dev に web-server-bundle が増えるだけ。

アノテーションの有効化

composer req annotations

脆弱性のチェック

composer require sensiolabs/security-checker --dev

db 設定

.env

DATABASE_URL=mysql://db_user:db_password@127.0.0.1:3306/db_name

上記を変更する

DATABASE_URL=pgsql://db_user:db_password@localhost:5432/db_name

config/packages/doctrine.yaml

    dbal:
        # configure these for your database server
        driver: 'pdo_pgsql'
        server_version: '11.0'
        charset: utf8
        default_table_options:
            charset: utf8
            collate: utf8_unicode_ci

        url: '%env(resolve:DATABASE_URL)%'

User テーブル作成

❯ bin/console make:user

 The name of the security user class (e.g. User) [User]:
 >

 Do you want to store user data in the database (via Doctrine)? (yes/no) [yes]:
 >

 Enter a property name that will be the unique "display" name for the user (e.g. email, username, uuid) [email]:
 >

 Will this app need to hash/check user passwords? Choose No if passwords are not needed or will be checked/hashed by some other system (e.g. a single sign-on server).

 Does this app need to hash/check user passwords? (yes/no) [yes]:
 >

The newer Argon2i password hasher requires PHP 7.2, libsodium or paragonie/sodium_compat. Your system DOES support this algorithm.
You should use Argon2i unless your production system will not support it.

 Use Argon2i as your password hasher (bcrypt will be used otherwise)? (yes/no) [yes]:
 >

 created: src/Entity/User.php
 created: src/Repository/UserRepository.php
 updated: src/Entity/User.php
 updated: config/packages/security.yaml


  Success!


 Next Steps:
   - Review your new App\Entity\User class.
   - Use make:entity to add more fields to your User entity and then run make:migration.
   - Create a way to authenticate! See https://symfony.com/doc/current/security.html

~/testProjects/symfony4/server 11s

テーブル名を指定、user だと fixture でエラーがでる

 * @ORM\Table(name="system_user")

生成されたら、id のアノテーションを修正

  • strategy="IDENTITY" を追加する
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="IDENTITY")
     * @ORM\Column(type="integer")
     */
    private $id;
❯ bin/console make:migration


  Success!


 Next: Review the new migration "src/Migrations/Version20181109224910.php"
 Then: Run the migration with php bin/console doctrine:migrations:migrate
 See https://symfony.com/doc/current/bundles/DoctrineMigrationsBundle/index.html

~/testProjects/symfony4/server
❯ bin/console doc:mig:mig

fixture

composer require orm-fixtures --dev
❯ bin/console make:fixtures

 The class name of the fixtures to create (e.g. AppFixtures):
 > UserFixture

 created: src/DataFixtures/UserFixture.php


  Success!


 Next: Open your new fixtures class and start customizing it.
 Load your fixtures by running: php bin/console doctrine:fixtures:load
 Docs: https://symfony.com/doc/master/bundles/DoctrineFixturesBundle/index.html

UserFixture

<?php

namespace App\DataFixtures;

use App\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class UserFixture extends Fixture
{
    private $passwordEncoder;

    /**
     * UserFixture constructor.
     * @param $passwordEncoder
     */
    public function __construct(UserPasswordEncoderInterface $passwordEncoder)
    {
        $this->passwordEncoder = $passwordEncoder;
    }

    public function load(ObjectManager $manager)
    {
        $user = new User();

        $user->setEmail('hisashi@sunvisor.net');
        $user->setPassword($this->passwordEncoder->encodePassword(
            $user,
            'password'
        ));

        $manager->persist($user);
        $manager->flush();
    }
}
bin/console doctrine:fixtures:load

ログインフォーム

How to Build a Login Form (Symfony Docs)

> php bin/console make:auth
 What style of authentication do you want? [Empty authenticator]:
  [0] Empty authenticator
  [1] Login form authenticator
 > 1

 The class name of the authenticator to create (e.g. AppCustomAuthenticator):
 > LoginFormAuthenticator

 Choose a name for the controller class (e.g. SecurityController) [SecurityController]:
 >

 created: src/Security/LoginFormAuthenticator.php
 updated: config/packages/security.yaml
 created: src/Controller/SecurityController.php
 created: templates/security/login.html.twig


  Success!


 Next:
 - Customize your new authenticator.
 - Finish the redirect "TODO" in the App\Security\LoginFormAuthenticator::onAuthenticationSuccess() method.
 - Review & adapt the login template: templates/security/login.html.twig.

リダイレクト先の指定

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);
        }

        return new RedirectResponse($this->router->generate('home'));
    }

アクセス制御

ページならばコントローラーのメソッドに @IsGranted ノーテーションを入れる

/**
 *@IsGranted("ROLE_USER")
 */*

api の場合はどうするのか

$this->denyAccessUnlessGranted('ROLE_ADMIN');

これだとログインフォームに遷移してしまいそう

apiToken フィールド

コントローラーの生成

bin/console make:controller
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment