Symfony のセキュリティ
Security の指示に従ってインストール
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": "*"
},
こちらはほぼ何も入っていない
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
.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)%'
❯ 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
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
<?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');
これだとログインフォームに遷移してしまいそう
bin/console make:controller