首页 > 解决方案 > 如何解决 Symfony 5.1.5 上的 Lexit JWT 401 错误“由于系统问题无法处理身份验证请求”

问题描述

我是 Symfony 的新手,遇到了一个我自己无法解决的问题。

我已经建立了一个非常基本的网站,并使用 API 平台公开了一个基本的 API。我想尝试构建一个 SPA(如Symfony 中所述:快速通道),并为用户添加身份验证。我选择了lexik_jwt_authentication 包并按照官方 repo中描述的步骤进行操作。

我使用 Security 包的 Symfony 默认 UserProvider 部分。

我在 Ubuntu 18.04 上运行 Symfony 5.1.5 和 PHP 7.4.10 和 MYSQL 5.7.31。我使用 Symfony 提供的内置服务器symfony server:start

以下是配置:

配置 > 包 > lexik_jwt_authentication.yaml

lexik_jwt_authentication:
    secret_key: '%env(resolve:JWT_SECRET_KEY)%'
    public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
    pass_phrase: '%env(JWT_PASSPHRASE)%'

配置 > 包 > security.yaml

security:
    encoders:
        App\Entity\User:
            algorithm: auto

    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\User
       
                
    firewalls:    
        login:
            pattern:  ^/api/login
            stateless: true
            anonymous: true
            json_login:
                check_path:               /api/login_check
                success_handler:          lexik_jwt_authentication.handler.authentication_success
                failure_handler:          lexik_jwt_authentication.handler.authentication_failure

        api:
            pattern:   ^/api
            stateless: true
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator

        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
            
        main:
            anonymous: true
            lazy: true
            provider: app_user_provider
            guard:
                authenticators:
                    - App\Security\AppUserAuthenticator
                    
            logout:
                path: app_logout
                # where to redirect after logout
                # target: app_any_route

    
    access_control:
        - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }
        - { path: ^/admin, roles: ROLE_ADMIN }
        - { path: ^/seance, roles: ROLE_USER }
        - { path: ^/profile, roles: ROLE_USER }
        - { path: ^/dashboard, roles: ROLE_USER }
        

配置 > 路由.yaml

user_profile:
    path:       /profile/{slug}
    controller: App\Controller\AppUserController::profile

api_login_check:
    path: /api/login_check

src > 实体 > 用户

<?php

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\String\Slugger\SluggerInterface;

/**
 * @ORM\Entity(repositoryClass=UserRepository::class)
 * @UniqueEntity(fields={"username","slug"}, message="Il y a déjà un compte avec ce pseudo")
 * 
 */
class User implements UserInterface
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * 
     */
    private $id;

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

    /**
     * @ORM\Column(type="json")
     * 
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

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

    /**
     * @ORM\Column(type="json", nullable=true)
     */
    private $seance_collection = [];

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

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

    /**
     * @ORM\Column(type="boolean")
     * 
     */
    private $isVerified = false;

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

    /**
     * @ORM\ManyToMany(targetEntity=Seance::class, inversedBy="users")
     * 
     */
    private $seances;

    /**
     * @ORM\ManyToOne(targetEntity=Type::class, inversedBy="users")
     * 
     */
    private $types;

    /**
     * @ORM\OneToMany(targetEntity=Progression::class, mappedBy="user")
     * 
     */
    private $progressions;

    public function __construct()
    {
        $this->seances = new ArrayCollection();
        $this->progressions = new ArrayCollection();
    }

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

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

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string) $this->username;
    }

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

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getPassword(): string
    {
        return (string) $this->password;
    }

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

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    public function getFirstname(): ?string
    {
        return $this->firstname;
    }

    public function setFirstname(?string $firstname): self
    {
        $this->firstname = $firstname;

        return $this;
    }

    public function getSeanceCollection(): ?array
    {
        return $this->seance_collection;
    }

    public function setSeanceCollection(?array $seance_collection): self
    {
        $this->seance_collection = $seance_collection;

        return $this;
    }

    public function getAge(): ?int
    {
        return $this->age;
    }

    public function setAge(?int $age): self
    {
        $this->age = $age;

        return $this;
    }

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

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

        return $this;
    }

    public function isVerified(): bool
    {
        return $this->isVerified;
    }

    public function setIsVerified(bool $isVerified): self
    {
        $this->isVerified = $isVerified;

        return $this;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

    public function computeSlug(SluggerInterface $slugger){
        if (!$this->slug || '- ' == $this->slug){
            $this->slug = (string) $slugger->slug((string) $this)->lower();
        }
    }

    public function getIsVerified(): ?bool
    {
        return $this->isVerified;
    }

    /**
     * @return Collection|Seance[]
     */
    public function getSeances(): Collection
    {
        return $this->seances;
    }

    public function addSeance(Seance $seance): self
    {
        if (!$this->seances->contains($seance)) {
            $this->seances[] = $seance;
        }

        return $this;
    }

    public function removeSeance(Seance $seance): self
    {
        if ($this->seances->contains($seance)) {
            $this->seances->removeElement($seance);
        }

        return $this;
    }

    public function getTypes(): ?Type
    {
        return $this->types;
    }

    public function setTypes(?Type $types): self
    {
        $this->types = $types;

        return $this;
    }

    /**
     * @return Collection|Progression[]
     */
    public function getProgressions(): Collection
    {
        return $this->progressions;
    }

    public function addProgression(Progression $progression): self
    {
        if (!$this->progressions->contains($progression)) {
            $this->progressions[] = $progression;
            $progression->setUser($this);
        }

        return $this;
    }

    public function removeProgression(Progression $progression): self
    {
        if ($this->progressions->contains($progression)) {
            $this->progressions->removeElement($progression);
            // set the owning side to null (unless already changed)
            if ($progression->getUser() === $this) {
                $progression->setUser(null);
            }
        }

        return $this;
    }
}

src > 控制器 > AppUserController

<?php

namespace App\Controller;

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

use Doctrine\ORM\EntityManagerInterface;
use App\Repository\UserRepository;
use App\Entity\User;
use Twig\Environment;

use App\Form\UserType;


class AppUserController extends AbstractController
{

    public function __construct(Environment $twig,EntityManagerInterface $entityManager){
        $this->twig = $twig;
        $this->entityManager = $entityManager;
    }

    /**
     * @Route("/login", name="app_login")
     */
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        if ($this->getUser()) {
             return $this->redirectToRoute('seance_home');
        }

        // 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', ['last_username' => $lastUsername, 'error' => $error]);
    }

    

    /**
     * @Route("/logout", name="app_logout")
     */
    public function logout()
    {
        throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
    }
    
    

    /**
     * @Route("/profile/{slug}", name="user_profile")
     */
    public function profile($slug, UserRepository $userRepository){
        
        return new Response($this->twig->render('user/profile.html.twig',[
            'user' => $userRepository->findOneBy(['slug'=>$slug]),
        ]));
    }
    /**
     * @Route("/profile/{slug}/editer", name="user_profile_edit")
     */

    public function editProfile($slug,Request $request, UserRepository $userRepository){
        
        $user = $this->getUser();
        
        $form = $this->createForm(UserType::class, $user);

        $form->handleRequest($request);

        //$lengthToCompute = $form->getData()->getExercises();
        //dump($lengthToCompute);

        if ($form->isSubmitted() && $form->isValid()) {
            // ... do your form processing, like saving the Seance and Exercise entities
            $user = $form->getData();
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();
            //dump($seance);

            return $this->redirectToRoute("user_profile",["slug" => $user->getSlug()]);
        }else{
            return $this->render('user/edit.html.twig', [
                'form' => $form->createView(),
                'title' => "Modifie ton profil",
        
            ]);
        }
    }

    /**
     * @Route("/dashboard/{slug}", name="user_dashboard")
     */
    public function dashboard($slug, UserRepository $userRepository){
        $user = $userRepository->findOneBy(['slug'=>$slug]);
        $entityManager = $this->getDoctrine()->getManager();

          
        $query = $entityManager->createQuery(
            'SELECT p.event,count(p.id)
            FROM App\Entity\Progression p
            WHERE p.user = :user
            GROUP BY p.event
            '
        )->setParameter('user', $user->getId());
        
        $seance_completion_data = $query->getResult();

        $query2 = $entityManager->createQuery(
            'SELECT (s.title),count(p.id)
            FROM App\Entity\Progression p
            INNER JOIN App\Entity\Seance s
            WHERE p.seance=s AND p.user = :user AND p.event= :evt
            GROUP BY s.title
            '
        )->setParameters(array('user'=> $user->getId(),'evt' => "finish"));
        //->setParameter('event', "finish");

         $seance_prefered_data = $query2->getResult();


        

        return new Response($this->twig->render('user/dashboard.html.twig',[
            'user' => $user,
            'seance_completion_data' => $seance_completion_data,
            'seance_prefered_data' => $seance_prefered_data
        ]));
    }

    public function api()
    {
        return new Response(sprintf('Logged in as %s', $this->getUser()->getUsername()));
    }

    
}

现在,当我:

curl -X POST -H "Content-Type: application/json" https://127.0.0.1:8001/api/login_check -d '{"username":"SOME_USER","password":"SOME_PASSWORD"}

我有 :

{"code":401,"message":"由于系统问题,无法处理身份验证请求。"}

这并没有提供太多关于我的问题根源的信息。

服务器记录输出:

[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    127.0.0.1:33222 Accepted path="/usr/bin/php7.4" php="7.4.10"
[Web Server/PHP ] Sep 24 09:53:21 |INFO | PHP    Matched route "api_login_check". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |INFO | PHP    Authentication request failed. 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DebugHandlersListener::configure". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ValidateRequestListener::onKernelRequest". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.request" to listener "Nelmio\CorsBundle\EventListener\CorsListener::onKernelRequest". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\SessionListener::onKernelRequest". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::setDefaultLocale". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.request" to listener "ApiPlatform\Core\Filter\QueryParameterValidateListener::onKernelRequest". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleAwareListener::onKernelRequest". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.request" to listener "Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener::configureLogoutUrlGenerator". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.request" to listener "Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener::onKernelRequest". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Listener "Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener::onKernelRequest" stopped propagation of the event "kernel.request". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Listener "ApiPlatform\Core\EventListener\AddFormatListener::onKernelRequest" was not called for event "kernel.request". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Listener "ApiPlatform\Core\EventListener\ReadListener::onKernelRequest" was not called for event "kernel.request". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Listener "ApiPlatform\Core\Security\EventListener\DenyAccessListener::onSecurity" was not called for event "kernel.request". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Listener "ApiPlatform\Core\EventListener\DeserializeListener::onKernelRequest" was not called for event "kernel.request". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Listener "ApiPlatform\Core\Security\EventListener\DenyAccessListener::onSecurityPostDenormalize" was not called for event "kernel.request". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Listener "ApiPlatform\Core\Bridge\Symfony\Bundle\EventListener\SwaggerUiListener::onKernelRequest" was not called for event "kernel.request". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "Nelmio\CorsBundle\EventListener\CorsListener::onKernelResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "Nelmio\CorsBundle\EventListener\CacheableResponseVaryListener::onResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "ApiPlatform\Core\Hydra\EventListener\AddLinkHeaderListener::onKernelResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |WARN | SERVER POST (401) /api/login_check host="127.0.0.1:8004" ip="127.0.0.1" scheme="https"
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     path="/usr/bin/php7.4" php="7.4.10"
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::onKernelResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "Symfony\Component\WebLink\EventListener\AddLinkHeaderListener::onKernelResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "Symfony\Component\Security\Http\RememberMe\ResponseListener::onKernelResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\HttpCacheListener::onKernelResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "ApiPlatform\Core\HttpCache\EventListener\AddHeadersListener::onKernelResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ErrorListener::removeCspHeader". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener::onKernelResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\DisallowRobotsIndexingListener::onResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\SessionListener::onKernelResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\StreamedResponseListener::onKernelResponse". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelFinishRequest". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\SessionListener::onFinishRequest". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelFinishRequest". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.finish_request" to listener "Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener::onKernelFinishRequest". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleAwareListener::onKernelFinishRequest". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    Notified event "kernel.terminate" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelTerminate". 
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP     
[Web Server/PHP ] Sep 24 09:53:21 |DEBUG| PHP    127.0.0.1:33222 Closing 

当我要求 curl 详细时:

Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 8001 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (OUT), TLS change cipher, Client hello (1):
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS Unknown, Certificate Status (22):
* TLSv1.3 (IN), TLS handshake, Unknown (8):
* TLSv1.3 (IN), TLS Unknown, Certificate Status (22):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS Unknown, Certificate Status (22):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.3 (IN), TLS Unknown, Certificate Status (22):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.3 (OUT), TLS Unknown, Certificate Status (22):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_128_GCM_SHA256
* ALPN, server accepted to use h2
* Server certificate:
*  subject: O=Symfony dev cert; OU=nico@nicodeforge
*  start date: Sep 21 10:11:49 2020 GMT
*  expire date: Dec 25 11:11:49 2022 GMT
*  subjectAltName: host "127.0.0.1" matched cert's IP address!
*  issuer: O=Symfony dev CA; OU=nico@nicodeforge; CN=Symfony nico@nicodeforge
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* TLSv1.3 (OUT), TLS Unknown, Unknown (23):
* TLSv1.3 (OUT), TLS Unknown, Unknown (23):
* TLSv1.3 (OUT), TLS Unknown, Unknown (23):
* Using Stream ID: 1 (easy handle 0x561f9c95f710)
* TLSv1.3 (OUT), TLS Unknown, Unknown (23):
> POST /api/login_check HTTP/2
> Host: 127.0.0.1:8001
> User-Agent: curl/7.58.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 37
> 
* TLSv1.3 (IN), TLS Unknown, Certificate Status (22):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS Unknown, Unknown (23):
* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
* TLSv1.3 (OUT), TLS Unknown, Unknown (23):
* TLSv1.3 (OUT), TLS Unknown, Unknown (23):
* We are completely uploaded and fine
* TLSv1.3 (IN), TLS Unknown, Unknown (23):
* TLSv1.3 (IN), TLS Unknown, Unknown (23):
* TLSv1.3 (IN), TLS Unknown, Unknown (23):
< HTTP/2 401 
< cache-control: no-cache, private
< content-type: application/json
< date: Thu, 24 Sep 2020 07:53:21 GMT
< date: Thu, 24 Sep 2020 07:53:21 GMT
< host: 127.0.0.1:8001
< link: <https://127.0.0.1:8001/endpoint/docs.jsonld>; rel="http://www.w3.org/ns/hydra/core#apiDocumentation"
< www-authenticate: Bearer
< x-debug-token: 11f030
< x-debug-token-link: https://127.0.0.1:8001/_profiler/11f030
< x-powered-by: PHP/7.4.10
< x-robots-tag: noindex
< content-length: 95
< 
* TLSv1.3 (IN), TLS Unknown, Unknown (23):
* Connection #0 to host 127.0.0.1 left intact
{"code":401,"message":"Authentication request could not be processed due to a system problem."}

我的第一个猜测是 security.yaml 的错误配置,我试图将登录提供程序“强制”为“app_user_provider”=> 没有任何区别。

我的第二个猜测是我的 AppUserController 有问题,但我不知道如何处理它。

我在网上做了一些研究。我能找到的所有答案都是“我没有正确设置我的 DATABASE_URL”,我很确定我对此很满意,因为我可以使用登录表单对我的网站上的用户进行身份验证。

同时,我将进行全新的 Symfony 安装,看看是否能够将 JWT 捆绑包与更轻的项目一起使用。

标签: symfony5lexikjwtauthbundle

解决方案


好的,所以我因为 security.yaml 中缺少的一行而损失了一整天。

通过添加“属性:用户名”解决了我的问题:

security:
    encoders:
        App\Entity\User:
            algorithm: auto

    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\User
                property: username

老实说,我真的不明白它解决问题的原因。但它确实:)

感谢所有花时间阅读的人。希望这会帮助一些人!

我做的第二件事是将我的私有和公共封装在 base64 中,如此所述。虽然一开始并没有解决问题。


推荐阅读