先,放个目录:
2、通过symfony的security实现用mysql用户表登录
3、easyAdmin bundle创建的用户记录密码没加密的问题
之前用symfony3.4一直感觉他太重了,最上手symfony5发现加入了很多新特性,搭配easyadminBundle、api-platform这些用起来感觉简直如有神助,瞬间爱了。
不过api-platform还没太弄明白,有用这个的可以给分享下文档,官网的文档说的太简略了。|||
下面记一些使用时遇到的小问题:
ps:安装直接按官网文档composer就行,这里就跳过了;
1、配置mysql
文档说配置到 /config/doctrine.yml
实际上doctrine.yml又读取了根目录下的.env文件的DATABASE_URL的值,所以可以直接对.env的DATABASE_URL配置。
# DATABASE_URL=mysql://username:[email protected]:3306/dbname?serverVersion=5.7 我的数据库没有密码,所以:后面直接跟了@ip:port
DATABASE_URL=mysql://root:@127.0.0.1:3306/fbm?serverVersion=5.7
2、通过symfony的security实现用mysql用户表登录
先说步骤,后面依次细说:
- 创建user entity类并实现UserInterface并把它更新到数据库(可以使用命令:php bin/console make:entity)
- 把user类配置为用户提供者,并配置密码加密算法
- 创建防火墙认证器(用于登录验证等… 使用命令:php bin/console make:auth)
- 给数据库的user表添加用户
- 测试登录
1、依次执行:
php bin/console make:entity # 创建enity并根据提示添加usernam、password、roles、salt等字段
# tips:roles建议array类型
php bin/console doctrine:schema:update --force --dump-sql #把enity更新到数据库
2、在config/package/security.yml的security添加如下配置:
providers:
users_in_memory: { memory: null }
users:
entity:
# 这个entity类用来提供用户
class: 'App\Entity\User'
# the property to query by - e.g. username, email, etc
property: 'username'
encoders:
# use your user class name here
App\Entity\User:
# Use native password encoder 配置密码加密算法
# This value auto-selects the best possible hashing algorithm
# (i.e. Sodium when available).
algorithm: sha256
encode_as_base64: true
iterations: 1 # 循环次数
3、执行如下命令创建验证器:
php bin/console make:auth
# 以下是输出内容,根据提示按实际情况填写就好。。。
What style of authentication do you want? [Empty authenticator]:
[0] Empty authenticator
[1] Login form authenticator
> 1
1[K
The class name of the authenticator to create (e.g. AppCustomAuthenticator):
> LoginFormAuthenticator #### 验证器类名
Choose a name for the controller class (e.g. SecurityController) [SecurityController]:
>
Enter the User class that you want to authenticate (e.g. App\Entity\User) [App\Entity\Us
>
Which field on your App\Entity\User class will people enter when logging in? [username]:
[0] id
[1] username
[2] email
[3] password
[4] roles
[5] salt
[6] created_at
[7] updated_at
>
Do you want to generate a '/logout' URL? (yes/no) [yes]:
>
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\LoginFormA
- Check the user's password in App\Security\LoginFormAuthen
- Review & adapt the login template: templates/security/log
修改验证器类的checkCredentials方法为:
// src/Security/LoginFormAuthenticator.php
public function checkCredentials($credentials, UserInterface $user)
{
return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
}
其他两部就不细说了。
3、easyAdmin bundle创建的用户记录密码没加密的问题
要解决这个问题--- more》,可以:
-
改写user entity的setPassword方法为(github的大佬说这种方法破环了封装,我:挺适合我|||):
public function setPassword(string $password): self { global $kernel; if (method_exists($kernel, 'getKernel')) $kernel = $kernel->getKernel(); $this->password = $kernel->getContainer()->get('security.password_encoder')->encodePassword($this, $password); return $this; }
- 或者实现AdminController和如下关键的几个方法,并且将config/route/easy_admin.yml做如下配置:
easy_admin_bundle:
resource: 'App\Controller\AdminController'
prefix: /admin
type: annotation
<?php
/*
* @Author: l.jirong [email protected]
* @Date: 2020-03-07 09:55:18
* @LastEditors: l-jirong [email protected]
* @LastEditTime: 2020-03-08 00:13:44
* @Description: file content
*/
namespace App\Controller;
use App\Entity\User;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class AdminController extends EasyAdminController
{
protected function persistUserEntity($user)
{
$encodedPassword = $this->encodePassword($user, $user->getPassword());
$user->setPassword($encodedPassword);
parent::persistEntity($user);
}
protected function updateUserEntity($user)
{
$encodedPassword = $this->encodePassword($user, $user->getPassword());
$user->setPassword($encodedPassword);
parent::updateEntity($user);
}
private function encodePassword($user, $password)
{
$passwordEncoderFactory = new EncoderFactory([
// 这里的sha256以及后面的参数要和security.yml里的配置相同,否则加密后登录验证通不过
User::class => new MessageDigestPasswordEncoder('sha256',true,1)
]);
$encoder = $passwordEncoderFactory->getEncoder($user);
return $encoder->encodePassword($password, $user->getSalt());
}
}
3、文件上传,从请求对象中获取文件和文件名等信息
//文档: https://symfony.com/doc/current/controller/upload_file.html
$this->request->files->get('imageresource'); // imageresource entity类名(小写)
// 获取文件名: ->getClientOriginalName()
这些都是经过好几天的时间摸索出来的 : ( 。。|||,当然,搜索引擎帮了很多忙。)