php - 如何确定登录表单(Symfony 4)拒绝访问的原因?

标签 php symfony login error-handling

src/Entity/User.php:

<?php

namespace App\Entity;

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

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

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

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

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

    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

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

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

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

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

    public function getRoles()
    {
        return array('ROLE_USER');
    }

    public function eraseCredentials()
    {
    }

    /** @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]);
    }
}

config/packages/security.yaml:
security:
    encoders:
        App\Entity\User:
            algorithm: bcrypt

    # ...

    providers:
        our_db_provider:
            entity:
                class: App\Entity\User
                property: username
                # if you're using multiple entity managers
                # manager_name: customer

    firewalls:
        main:
            anonymous: ~
            form_login:
                login_path: login
                check_path: login

    # ...
    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, roles: ROLE_ADMIN }

src/Repository/UserRepository.php
    namespace App\Repository;

    use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface;
    use Doctrine\ORM\EntityRepository;

    class UserRepository extends EntityRepository implements UserLoaderInterface
    {
        public function loadUserByUsername($username)
        {
            return $this->createQueryBuilder('u')
                ->where('u.username = :username OR u.email = :email')
                ->setParameter('username', $username)
                ->setParameter('email', $username)
                ->getQuery()
                ->getOneOrNullResult();
        }
    }

src/Controller/SecurityController.php

<?php

namespace App\Controller;

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

class SecurityController extends Controller
{
  /**
  * @Route("/login", name="login")
  */
  public function login(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,
    ));
  }
}

登录时出现错误:

Access Denied.

Uncaught PHP Exception Symfony\Component\Security\Core\Exception\AccessDeniedException: "Access Denied." at /Users/work/project/vendor/symfony/security/Http/Firewall/AccessListener.php line 68

最佳答案

从安全配置中,您要求所有经过身份验证的用户都应具有ROLE_ADMIN角色(登录页面除外)才能访问页面。当用户登录时,他将只具有ROLE_USER角色tho。 (请参阅您的用户实体)。

要解决您的问题,请执行以下操作:将ROLE_ADMIN角色添加到用户实体,或更改安全性配置以允许仅使用ROLE_USER的用户。

- { path: ^/, roles: ROLE_USER }

关于php - 如何确定登录表单(Symfony 4)拒绝访问的原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51117301/

相关文章:

php - AbstractSmtpTransport.php 中的 Swift_TransportException 第 404 行 : Connection to smtp. gmail.com:465 超时

php - strip_tags() 容易受到脚本攻击吗?

mongodb - Symfony 2 StofDoctrineExtensionBundle 时间戳与 odm (MongoDB)

mysql - Doctrine DBAL 查询构建器连接和 where 子句

php - 在 1and1 托管中发送邮件时遇到问题

login - 如何使用 Spring Security 实现登录限制?

php - MySQL数据库表设置

drupal - Style Drupal 7登录页面

grails - Grails如何使用过滤器进行页面登录检查

php - 刷新PHP sql查询而不刷新页面