php - Symfony 4 简单的 form_login 不起作用

标签 php symfony doctrine symfony4

Symfony 新手。我对此感到困惑并挣扎了几个小时。我正在关注this官方文档中的“传统登录表单”教程。

此外,我还配置了从数据库加载用户,如 here 中所示。 。我已经从另一个应用程序导入了数据库表,但我只需要安全/身份验证内容的 Doctrine 。

我已经检查了所有必要的文件,似乎与教程中的文件类似,但我的登录表单仍然不起作用。它不会抛出错误或任何东西。它只是默默地失败,每当我点击提交时,在前端它看起来就像刷新但在后端肯定有东西没有插入。

我清除了所有的 Doctrine 缓存、 Composer 缓存和 bin/控制台缓存。

我已经检查过多次的文件。

.env

 # This file is a "template" of which env vars need to be defined for your application
# Copy this file to .env file for development, create environment variables when deploying to production

###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=e239b1ba76d53407cbae30849fc489b9
#TRUSTED_PROXIES=127.0.0.1,127.0.0.2
#TRUSTED_HOSTS=localhost,example.com
###< symfony/framework-bundle ###

###> symfony/swiftmailer-bundle ###
# For Gmail as a transport, use: "gmail://username:password@localhost"
# For a generic SMTP server, use: "smtp://localhost:25? encryption=&auth_mode="
# Delivery is disabled by default via "null://localhost"
MAILER_URL=null://localhost
###< symfony/swiftmailer-bundle ###

###> doctrine/doctrine-bundle ###
# Format described at http://docs.doctrine-project.org/projects/doctrine- 
dbal/en/latest/reference/configuration.html#connecting-using-a-url
# For an SQLite database, use: "sqlite:///%kernel.project_dir%/var/data.db"
# Configure your db driver and server_version in 
config/packages/doctrine.yaml

DATABASE_URL=mysql://root:@127.0.0.1:3306/symfony_test_db
###< doctrine/doctrine-bundle ###

Security.yaml

security:
encoders:
    App\Entity\User:
        algorithm: bcrypt
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
    our_db_provider:
        entity:
            class: App\Entity\User
            property: username
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        anonymous: true
        provider: our_db_provider
        form_login:
            login_path: login
            check_path: login

    access_control:
    # - { path: ^/admin, roles: ROLE_ADMIN }
    # - { path: ^/profile, roles: ROLE_USER }

src/Entity/User.php

 <?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface, \Serializable
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=25, nullable=true)
 */
private $username;

/**
 * @ORM\Column(type="string", length=64, nullable=true)
 */
private $password;

/**
 * @ORM\Column(type="string", length=254, nullable=true)
 */
private $email;

/**
 * @ORM\Column(type="boolean", nullable=true)
 */
private $isactive;

/**
 * @ORM\Column(type="string", nullable=true)
 */
private $apiKey;


public function __construct()
{
    $this->isActive = true;
    // may not be needed, see section on salt below
    // $this->salt = md5(uniqid('', true));
}

public function getId()
{
    return $this->id;
}

public function getUsername(): ?string
{
    return $this->username;
}

public function setUsername(?string $username): self
{
    $this->username = $username;

    return $this;
}

public function getPassword(): ?string
{
    return $this->password;
}

public function setPassword(?string $password): self
{
    $this->password = $password;

    return $this;
}

public function getEmail(): ?string
{
    return $this->email;
}

public function setEmail(?string $email): self
{
    $this->email = $email;

    return $this;
}

public function getIsactive(): ?bool
{
    return $this->isactive;
}

public function setIsactive(?bool $isactive): self
{
    $this->isactive = $isactive;

    return $this;
}

public function getSalt()
{
    // you *may* need a real salt depending on your encoder
    // see section on salt below
    return null;
}

//Abstract methods implementation

public function getRoles()
{
    // TODO: Implement getRoles() method.
    return array('ROLE_USER');
}

public function eraseCredentials()
{
    // TODO: Implement eraseCredentials() method.
}

/** @see \Serializable::serialize() */
public function serialize()
{
    return serialize(array(
        $this->id,
        $this->username,
        $this->password,
        // see section on salt below
        // $this->salt,
    ));
}

/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
    list (
        $this->id,
        $this->username,
        $this->password,
        // see section on salt below
        // $this->salt
        ) = unserialize($serialized, ['allowed_classes' => false]);
}
}

src/Repository/UserRepository.php#

<?php

namespace App\Repository;

use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
 * @method User|null find($id, $lockMode = null, $lockVersion = null)
 * @method User|null findOneBy(array $criteria, array $orderBy = null)
 * @method User[]    findAll()
 * @method User[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class UserRepository extends ServiceEntityRepository
{
    public function __construct(RegistryInterface $registry)
    {
    parent::__construct($registry, User::class);
    }
}

src/Controller/SecurityController.php

<?php

namespace App\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Debug\Debug;
use Psr\Log\LoggerInterface;

class SecurityController extends Controller {


public function index(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,
        )
    );
  }
}

login.html.twig

{% if error %}
<div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}

<form action="{{ path('app_security_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" />

<button type="submit">login</button>

用户表架构

id,username,password,is_active,email

编辑添加路由.yml

app_lucky_number:
   path: /lucky/number
   controller: App\Controller\LuckyController::index

app_security_login:
   path: /login
   controller: App\Controller\SecurityController::index
app_home:
   path: /
   controller: App\Controller\IBController::home

我不确定我错过了什么。

最佳答案

感谢大家对问题部分发表评论,错误只是在 security.yaml 文件中。

login_pathcheck_path 处,将它们与路径名称而不是实际路径相关联。

所以为了纠正我改变了

login_path: app_security_login
check_path: app_security_login

关于php - Symfony 4 简单的 form_login 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50255600/

相关文章:

.htaccess - 使用 .htaccess 将所有 url 重定向到 https,图像除外(在 Symfony2 中)

zend-framework - 使用 Doctrine ODM 将 Zend Framework 1.11 与 MongoDB 集成

php - Doctrine 2 自定义 ObjectMultiCheckbox 值

php - 根据当前登录用户获取表详细信息

php - php中top.location的等价物是什么?

php - 如何将用户选择的csv文件导入数据库

在 csv 中未检测到 php 换行符

html - 以 Symfony 形式编辑复选框列表的 View

mysql - 相同的Id,不同的值,如果一个不OK,排除所有id

php - Symfony Doctrine ORM CLI 字体/颜色不起作用?