Silex:身份验证系统无法登录

时间:2017-08-30 10:41:10

标签: symfony security authentication login silex

我正在尝试在我的Silex项目中实现身份验证系统。但是,我无法让它发挥作用。我已经咨询了很多涉及这个系统的网站,但是将它们组合在一起仍然无法使我的项目有效。

首先,我在localhost中使用ICT4LIFE文件夹。我的整个项目都在那个文件夹中。现在,这是我的提供者注册:

$app->register(new Silex\Provider\SecurityServiceProvider(), array(
            'security.firewalls' => array(
                'user' => array(
                    'pattern' => '^ICT4LIFE/user/',
                    'form' => array('login_path' => 'ICT4LIFE/', 'check_path' => '/user/login_check'),
                    'logout' => array('logout_path' => '/user/logout'),
                    'anonymous' => true,
                    'users' => function () use ($app) {
                        return new Models\UserProvider($app['db']);
                    }
                ),
            ),
            'security.access_rules' => array(
                array('^ICT4LIFE/user/', 'ROLE_USER')
            )
        ));

然后,当然是我们要登录的主页:

$routes->match('/', function (Request $request) use ($app) {

    $form = $app['form.factory']->createBuilder(FormType::class)
        ->add('username', TextType::class, array(
            'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 3,'max' => 20))),
            'label' => 'Username',
            'required' => 'required',
            'attr' => array('class' => 'input-field', 'autocomplete' => 'off', 'placeholder' => 'Gebruikersnaam'),
            'label_attr' => array('class' => 'label'),
            'error_bubbling' => true
        ))
        ->add('password', PasswordType::class, array(
            'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5))),
            'label' => 'Password',
            'required' => 'required',
            'attr' => array('class' => 'input-field', 'autocomplete' => 'off', 'placeholder' => 'Wachtwoord'),
            'label_attr' => array('class' => 'label'),
            'error_bubbling' => true
        ))
        ->add('submit', SubmitType::class, [
            'label' => 'Login',
            'attr' => array('class' => 'submit'),
        ])
        ->getForm();

    $form->handleRequest($request);

    if ('POST' == $request->getMethod()) {
        $data = $form->getData();

        $userProvider = new Models\UserProvider($app['db']);

        try {
            $duplicated = $userProvider->loadUserByUsername($data['username']);
        } catch (Exception $e) {
            $duplicated = false;
        }

        if ($form->isValid() && !$duplicated) {
            $user = new \Symfony\Component\Security\Core\User\User($data['username'], '', array('ROLE_USER'));

            $encoder = $app['security.encoder_factory']->getEncoder($user);

            $insertion = $app['db']->insert(
                'users',
                array(
                    'username'    => $data['username'],
                    'password' => $encoder->encodePassword($data['password'], $user->getSalt()),
                    'roles'    => 'ROLE_USER'
                )
            );
        }
    }

    return $app['twig']->render('form.twig', [
        'error'         => $app['security.last_error']($request),
        'last_username' => $app['session']->get('_security.last_username'),
        'form' => $form->createView()
    ]);

})->bind('home');

你可能还需要我的树枝模板,所以就是这个(form.twig):

{% extends 'templates/app.twig' %}

{% block main %}
    {% if is_granted('ROLE_USER') %}
        <p>Welcome {{ app.security.token.user.username }}!</p>
        <p><a href="{{ path('logout') }}">Log out</a></p>
    {% endif %}
    {% if form is defined %}
        <div class="BasicForm">
        <div class="BasicForm-heading">Provide your information</div>
        {% if error is defined %}
            {{ error | raw }}
        {% endif %}
        <form action="" method="post">
            {{ form_widget(form) }}
        </form>
    {% endif %}
{% endblock %}

最后,我在网上找到的用户提供商:

<?php

namespace Models;

use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\DBAL\Connection;

class UserProvider implements UserProviderInterface
{
    private $conn;

    public function __construct(Connection $conn)
    {
        $this->conn = $conn;
    }

    public function loadUserByUsername($username)
    {
        $stmt = $this->conn->executeQuery('SELECT * FROM users WHERE username = ?', array(strtolower($username)));
        if (!$user = $stmt->fetch()) {
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
        }

        return new User($user['username'], $user['password'], explode(',', $user['roles']), true, true, true, true);
    }

    public function refreshUser(UserInterface $user)
    {
        if (!$user instanceof User) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
        }

        return $this->loadUserByUsername($user->getUsername());
    }

    public function supportsClass($class)
    {
        return $class === 'Symfony\Component\Security\Core\User\User';
    }
}

我的网站呈现没有问题。我无法访问此链接:http://localhost/ICT4LIFE/user/add 因为我然后被重定向到我的主页。不过,我可以访问此链接http://localhost/ICT4LIFE/user/register

在我的主页上,表单呈现得很好。我可以提供我的用户名和密码。但是,当我按Enter键时,页面似乎“刷新”。

这是我的sql表的图片,名为'users'。 enter image description here

此外,这是我过去常常访问的网页:

  

https://github.com/BeSimple/BeSimpleSsoAuthBundle/issues/27   https://blog.andrewshell.org/figuring-out-silex-securityserviceprovider/   https://silex.symfony.com/doc/2.0/providers/security.html   http://www.bubblecode.net/en/2012/08/28/mysql-authentication-in-silex-the-php-micro-framework/   http://symfony.com/doc/2.8/security.html

我相信应该只需要了解我的问题。其余的与我相信的安全无关。请让我知道我的问题是什么,或者您是否需要更多信息。

0 个答案:

没有答案