angularjs - 登录后symfony angularjs InsufficientAuthenticationException

标签 angularjs symfony http cookies authentication

大家好,

我在服务器端有 symfony 和 doctrine,在客户端有 Angularjs。我想创建一个登录端点。登录正常,我得到一个 PHPSESSID Cookie。

登录后我执行后续请求。在这个请求下我得到一个 InsufficientAuthenticationException:

Full authentication is required to access this resource. (500 Internal Server Error)

后续请求的头部:

Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0
Accept: application/json, text/plain, */*
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://localhost/frontend/admin/
Cookie: PHPSESSID=cllc3om5ascumuluofchu36aoc
DNT: 1
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

安全.yml:

security:
    encoders:
        App\Entity\User:
          algorithm: bcrypt
          cost: 20

    providers:
        database_users:
            entity: { class: App\Entity\User, property: username }
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: ~
            json_login:
                check_path: login

            logout:
                path: logout
                target: http://localhost/frontend/

    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/logout, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, roles: ROLE_USER  }

日志:

[2018-08-27 22:59:22] security.INFO: User has been authenticated successfully. {"username":"alex"} []
[2018-08-27 22:59:38] php.INFO: User Deprecated: Doctrine\Common\ClassLoader is deprecated. {"exception":"[object] (ErrorException(code: 0): User Deprecated: Doctrine\\Common\\ClassLoader is deprecated. at D:\\xampp\\htdocs\\symfony\\vendor\\doctrine\\common\\lib\\Doctrine\\Common\\ClassLoader.php:7)"} []
[2018-08-27 22:59:38] doctrine.DEBUG: SELECT t0.id AS id_1, t0.username AS username_2, t0.password AS password_3, t0.is_active AS is_active_4, t0.role AS role_5, t0.customer_id AS customer_id_6 FROM app_users t0 WHERE t0.id = ? [1] []
[2018-08-27 22:59:38] security.DEBUG: Token was deauthenticated after trying to refresh it. {"username":"alex","provider":"Symfony\\Bridge\\Doctrine\\Security\\User\\EntityUserProvider"} []
[2018-08-27 22:59:38] security.INFO: Populated the TokenStorage with an anonymous Token. [] []
[2018-08-27 22:59:38] security.DEBUG: Access denied, the user is not fully authenticated; redirecting to authentication entry point. {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException(code: 403):

我不知道我的错误在哪里或者我该如何调试这个问题。

编辑: 在 PHP 中登录:

    /**
     * @Route("/login", name="login")
     * @param Request $request
     * @return Response
     */
    public function login(Request $request)
    {
        $securityContext = $this->container->get('security.authorization_checker');
//        $tokenStorage = $this->container->get('security.token_storage');
//        $token = $tokenStorage->getToken();
//        var_dump($token);  => user has not Token!
        if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
            return new Response('http://localhost/frontend/admin/');
        } else {
            return new Response('', 500);
        }
    }

在 JS 中:

<script type="text/javascript">
    $( "#loginForm" ).submit(function( event ) {
        event.preventDefault();
        let $form = $(this);
        let username = $form.find( "input[name='username']" ).val();
        let password = $form.find( "input[name='password']" ).val();
        let data = "{";
        data += '"username": "'+username+'", ';
        data += '"password": "'+password+'" ';
        data += "}";

        $.ajax({
            method: 'post',
            url:'http://localhost/symfony/public/login',
            type:"POST",
            data:data,
            contentType:"application/json; charset=utf-8"
            //dataType:"json"
        }).done(function(response) {
            $(location).attr('href', response)
        }).fail(function() {
        });
    });
</script>

编辑 2: 用户实体:

namespace App\Entity;

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

/**
 * @ORM\Table(name="app_users")
 * @ORM\Entity()
 */
class User implements UserInterface, \Serializable, EquatableInterface
{
    /**
     * @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(name="is_active", type="boolean")
     */
    private $isActive;


    public function __construct()
    {
        $this->isActive = true;
    }

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

    public function getSalt()
    {
        return null;
    }

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

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

    public function eraseCredentials()
    {
        $this->password = null;
    }


    /** @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
            ) = unserialize($serialized, array('allowed_classes' => false));
    }

    public function isEqualTo(UserInterface $user)
    {
        if ($this->password !== $user->getPassword()) {
            return false;
        }

        if ($this->username !== $user->getUsername()) {
            return false;
        }

        return true;
    }
}

问候,

亚历克斯

最佳答案

token 在刷新时取消身份验证表明您的 User 类存在问题,如果它是最近的 (4+) Symfony,您的用户是否实现了 EquatableInterface 并具有 equals 方法?像....

class User implements EquatableInterface
{
    public function isEqualTo(UserInterface $user)
    {
        if ($this->password !== $user->getPassword()) {
            return false;
        }

        if ($this->salt !== $user->getSalt()) {
            return false;
        }

        if ($this->username !== $user->getUsername()) {
            return false;
        }

        return true;
    }
}

也许您可以将 User 类的源代码添加到您的问题中?

(引用 Token was deauthenticated after trying to refresh it)

关于angularjs - 登录后symfony angularjs InsufficientAuthenticationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52047010/

相关文章:

angularjs - 在 AngularJS http 数据字段中传递的数据

javascript - Angular JS 长按事件

django - Angular JS 和 Django

mysql - 在现有 OpenCart 数据库上使用 Doctrine 和 Symfony2

c++ - 未在 C++ 中使用 Curl 设置 HTTP header

javascript - $scope 数组不保存 ng-repeat 的值

symfony - 多文件验证 : "This value should be of type string"

php - 在 Symfony 2.1 中向 preUpdate 调用添加额外的持续调用

c# - 从另一个 Azure Function 启动 Azure Function 的最佳实践

css - 为什么我的字体文件没有下载没有加载?