身份验证不再有效

时间:2016-08-16 21:02:52

标签: php symfony orm

我正在与Symfony开展一个博客项目(我刚刚开始),到目前为止一直有效,直到我试图让选民只允许作者编辑和删除帖子(管理员除外)。< / p>

我不知道为什么但是(除了选民不起作用):  身份验证不再起作用,甚至登录也不起作用。它曾经工作但现在总是说:凭证无效。

如果有人可以提供帮助,我会非常非常高兴。这是我的文件: 谢谢!

如果您想查看任何文件来帮助我,我会非常乐意添加

安全:

security:
role_hierarchy:
    ROLE_ADMIN:     [ROLE_BLOGGER]

encoders:
    BlogBundle\Entity\User :
        algorithm: sha512
        iterations: 9616

# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
providers:
    our_db_provider:
        entity:
            class: BlogBundle:User
            property: username

firewalls:
    # disables authentication for assets and the profiler, adapt it according to your needs
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

    main:
        pattern: ^/
        anonymous: ~
        form_login:
            login_path: login
            check_path: login
            default_target_path: /post/
            always_use_default_target_path: true

        logout:
            path: logout
            target: /login

        remember_me:
            secret:   '%secret%'
            lifetime: 604800 # 1 week in seconds
            path:     /
        # activate different ways to authenticate

        # http_basic: ~
        # http://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate

        # form_login: ~
        # http://symfony.com/doc/current/cookbook/security/form_login_setup.html


access_control:
    - { path: ^/post/[0-9]+/edit, roles: [ROLE_ADMIN, ROLE_BLOGGER] }
    - { path: ^/post/[0-9]+/delete, roles: ROLE_ADMIN }
    - { path: ^/post/new, roles: [ROLE_ADMIN, ROLE_BLOGGER] }
    - { path: ^/user/[0-9]+/edit, roles: [ROLE_ADMIN] }
    - { path: ^/user/[0-9]+/delete, roles: [ROLE_ADMIN] }

服务:

parameters:


services:
    post_voter:
        class:      BlogBundle\Security\PostVoter
        arguments: ['@security.access.decision_manager']
        public:     false
        tags:
        - { name: security.voter }

<?php
namespace AppBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use BlogBundle\Entity\User;

class LoadUserData implements FixtureInterface, ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
private $container;

public function setContainer(ContainerInterface $container = null)
{
    $this->container = $container;
}

public function load(ObjectManager $manager)
{
    $userBlogger = new User();
    $userBlogger->setUsername('Blogger');
    $userBlogger->setSalt(base_convert(sha1(uniqid(mt_rand(), true)), 16, 36));
    $encoder = $this->container->get('security.password_encoder');
    $password = $encoder->encodePassword($userBlogger, 'fakepassword');
    $userBlogger->setPassword($password);
    $userBlogger->setRoles(array('ROLE_BLOGGER'));
    $userBlogger->setMail('blogger@hello.com');
    $manager->persist($userBlogger);

    $userAdmin = new User();
    $userAdmin->setUsername('Admin');
    $userAdmin->setSalt(base_convert(sha1(uniqid(mt_rand(), true)), 16, 36));
    $encoder = $this->container->get('security.password_encoder');
    $password = $encoder->encodePassword($userAdmin, 'fakepassword');
    $userAdmin->setPassword($password);
    $userAdmin->setRoles(array('ROLE_ADMIN'));
    $userAdmin->setMail('admin@hello.com');
    $manager->persist($userAdmin);
    $manager->flush();
}
}

发布控制器

<?php

namespace BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use BlogBundle\Entity\Post;
use BlogBundle\Form\PostType;
use BlogBundle\Entity\User;
use AppBundle\Security;

/**
* Post controller.
*/
class PostController extends Controller
{
/**
* Lists all Post entities.
*
*/
public function indexAction()
{
    $em = $this->getDoctrine()->getManager();

    $posts = $em->getRepository('BlogBundle:Post')->findAll();

    return $this->render('post/index.html.twig', array(
        'posts' => $posts,
    ));
}

/**
* Creates a new Post entity.
*
*/
public function newAction(Request $request)
{
    $post = new Post();
    $form = $this->createForm('BlogBundle\Form\PostType', $post);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $post->setCreated(new \DateTime());
        $post->setUpdated(NULL);
        $user = $this->getUser();
        $post->setAuthor($user);
        $em->persist($post);
        $em->flush();

        return $this->redirectToRoute('post_show', array('id' => $post->getId()));
    }

    return $this->render('post/new.html.twig', array(
        'post' => $post,
        'form' => $form->createView(),
    ));
}

/**
* Finds and displays a Post entity.
*
*/
public function showAction(Post $post)
{
    $deleteForm = $this->createDeleteForm($post);

    return $this->render('post/show.html.twig', array(
        'post' => $post,
        'delete_form' => $deleteForm->createView(),
    ));
}

/**
* Displays a form to edit an existing Post entity.
*/
public function editAction(Request $request, Post $post)
{
    $this->denyAccessUnlessGranted('edit', $post);
    $deleteForm = $this->createDeleteForm($post);
    $editForm = $this->createForm('BlogBundle\Form\PostType', $post);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $post->setUpdated(new \DateTime());
        $em->persist($post);
        $em->flush();

        return $this->redirectToRoute('post_edit', array('id' => $post->getId()));
    }

    return $this->render('post/edit.html.twig', array(
        'post' => $post,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}

/**
* Deletes a Post entity.
*
*/
public function deleteAction(Request $request, Post $post)
{
    $form = $this->createDeleteForm($post);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->remove($post);
        $em->flush();
    }

    return $this->redirectToRoute('post_index');
}

/**
* Creates a form to delete a Post entity.
*
* @param Post $post The Post entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(Post $post)
{
    return $this->createFormBuilder()
    ->setAction($this->generateUrl('post_delete', array('id' => $post->getId())))
    ->setMethod('DELETE')
    ->getForm()
    ;
}
}

会话控制器

<?php

namespace BlogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class SessionController extends Controller
{
/**
* @Route("/login")
*/

public function loginAction()
{
    $authenticationUtils = $this->get('security.authentication_utils');
    $error = $authenticationUtils->getLastAuthenticationError();

    if     ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY'))
    {
        // redirect authenticated users to homepage
        return $this->redirect($this->generateUrl('post_index'));
    }
    return $this->render('BlogBundle:Session:login.html.twig', array(
        'error'         => $error
    ));
}

}

选民:

<?php
namespace BlogBundle\Security;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use AppBundle\Entity\Post;

// Voter class requires Symfony 2.8 or higher version
class PostVoter extends Voter
{
const CREATE = 'create';
const EDIT   = 'edit';

/**
 * @var AccessDecisionManagerInterface
 */
private $decisionManager;

public function __construct(AccessDecisionManagerInterface $decisionManager)
{
    $this->decisionManager = $decisionManager;
}

protected function supports($attribute, $subject)
{
    if (!in_array($attribute, array(self::CREATE, self::EDIT))) {
        return false;
    }

    if (!$subject instanceof Post) {
        return false;
    }

    return true;
}

protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
    $user = $token->getUser();
    /** @var Post */
    $post = $subject; // $subject must be a Post instance, thanks to the supports method

    if (!$user instanceof UserInterface) {
        return false;
    }

    switch ($attribute) {
        case self::CREATE:
            // if the user is an admin, allow them to create new posts
            if ($this->decisionManager->decide($token, array('ROLE_ADMIN'))) {
                return true;
            }

            break;
        case self::EDIT:
            // if the user is the author of the post, allow them to edit the posts
            if ($user === $post->getAuthor()) {
                return true;
            }

            break;
    }

    return false;
}
}

1 个答案:

答案 0 :(得分:0)

谢谢大家的回答。 幸运的是,一个学说:fixtures:load修复了我的问题。对于邮件,这是因为我正在设置&#34; test@test.com"它认为&#34;测试&#34;不是有效的邮件。

谢谢