Я создаю API с помощью Symfony, и сейчас я пытаюсь создать токены JWT для моих пользователей.Я установил комплект аутентификации Lexik JWT.Но каждый раз, когда я пытаюсь сгенерировать токен с curl, он возвращает: {"code": 401, "message": "Bad credentials"}
Кто-нибудь знает, как я могу это исправить?
Я следовал этому руководству для установки lexikJWTAUthBundle: https://emirkarsiyakali.com/implementing-jwt-authentication-to-your-api-platform-application-885f014d3358
// security.yaml
security:
encoders:
App\Entity\User:
algorithm: brcrypt
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
entity_provider:
entity:
class: App\Entity\User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/login
stateless: true
anonymous: true
provider: entity_provider
form_login:
check_path: /login_check
provider: entity_provider
username_parameter : username
password_parameter : password
success_handler:
lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
require_previous_session: false
newuser:
pattern: ^/newuser
stateless: true
anonymous: true
api:
pattern: ^/api
stateless: true
anonymous: false
guard:
provider: entity_provider
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
main:
anonymous: true
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
// rout.yaml
newuser:
path: /newuser
controller: App\Controller\AuthController::newuser
methods: POST
api:
path: /api
controller: App\Controller\AuthController::api
login_check:
path: /login_check
methods: [POST]
// authController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\User;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class AuthController extends AbstractController
{
/**
* @Route("/newuser", name="new_user", methods="POST" )
* @return Response
*/
public function newuser(Request $request, UserPasswordEncoderInterface $encoder)
{
$em = $this->getDoctrine()->getManager();
$username = $request->request->get('_username');
$password = $request->request->get('_password');
$email = $request->request->get('_email');
$user = new User();
$user-> setName($username);
$user->setEmail($email);
$user->setPassword($encoder->encodePassword($user, $password));
$user->setCredit(3);
$user->setCreatedAt(new \DateTime());
$em->persist($user);
$em->flush();
return new Response(sprintf('User %s successfully created', $user->getUsername()));
}
public function api()
{
return new Response(sprintf('Logged in as %s', $this->getUser()->getUsername()));
}
}
// userEntity.php
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* User
*
* @ORM\Table(name="user")
* @ORM\Entity
*/
class User implements UserInterface
{
/**
* @var int
*
* @ORM\Column(name="id", type="bigint", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="email", type="string", length=255, nullable=false)
*/
private $email;
/**
* @var \DateTime
*
* @ORM\Column(name="created_at", type="datetime", nullable=false)
*/
private $createdAt;
/**
* @var string
*
* @ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private $password;
/**
* @var int|null
*
* @ORM\Column(name="credit", type="integer", nullable=true)
*/
private $credit;
/**
* @var \Doctrine\Common\Collections\Collection
*
* @ORM\ManyToMany(targetEntity="Badges", mappedBy="user")
*/
private $badges;
/**
* @var \Doctrine\Common\Collections\Collection
*
* @ORM\ManyToMany(targetEntity="Idea", inversedBy="user")
* @ORM\JoinTable(name="favorites",
* joinColumns={
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="idea_id", referencedColumnName="id")
* }
* )
*/
private $idea;
/**
* Constructor
*/
public function __construct()
{
$this->badges = new \Doctrine\Common\Collections\ArrayCollection();
$this->idea = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getCredit(): ?int
{
return $this->credit;
}
public function setCredit(?int $credit): self
{
$this->credit = $credit;
return $this;
}
// /**
// * @return Collection|Badges[]
// */
// public function getBadges(): Collection
// {
// return $this->badges;
// }
//
// public function addBadge(Badges $badge): self
// {
// if (!$this->badges->contains($badge)) {
// $this->badges[] = $badge;
// $badge->addUser($this);
// }
//
// return $this;
// }
//
// public function removeBadge(Badges $badge): self
// {
// if ($this->badges->contains($badge)) {
// $this->badges->removeElement($badge);
// $badge->removeUser($this);
// }
//
// return $this;
// }
// /**
// * @return Collection|Idea[]
// */
// public function getIdea(): Collection
// {
// return $this->idea;
// }
//
// public function addIdea(Idea $idea): self
// {
// if (!$this->idea->contains($idea)) {
// $this->idea[] = $idea;
// }
//
// return $this;
// }
//
// public function removeIdea(Idea $idea): self
// {
// if ($this->idea->contains($idea)) {
// $this->idea->removeElement($idea);
// }
//
// return $this;
// }
/**
* Returns the roles granted to the user.
*
* public function getRoles()
* {
* return ['ROLE_USER'];
* }
*
* Alternatively, the roles might be stored on a ``roles`` property,
* and populated in any number of different ways when the user object
* is created.
*
* @return (Role|string)[] The user roles
*/
public function getRoles()
{
return array('ROLE_USER');
}
/**
* Returns the salt that was originally used to encode the password.
*
* This can return null if the password was not encoded using a salt.
*
* @return string|null The salt
*/
public function getSalt()
{
// TODO: Implement getSalt() method.
}
/**
* Returns the username used to authenticate the user.
*
* @return string The username
*/
public function getUsername()
{
return $this->getName();
}
/**
* Removes sensitive data from the user.
*
* This is important if, at any given point, sensitive information like
* the plain-text password is stored on this object.
*/
public function eraseCredentials()
{
// TODO: Implement eraseCredentials() method.
}
}
// lexik_jwt_authentification.yaml
lexik_jwt_authentication:
private_key_path: '%env(resolve:JWT_SECRET_KEY)%'
public_key_path: '%env(resolve:JWT_PUBLIC_KEY)%'
pass_phrase: '%env(JWT_PASSPHRASE)%'