在Api Platform中配置JWT令牌并使用它作为身份验证机制,需要以下几个步骤:
安装LexikJWTAuthenticationBundle或其它JWT Bundle,例如LCobucciJWTBundle。
在config/packages/security.yaml中添加JWT配置:
security:
encoders:
App\Entity\User:
algorithm: auto
cost: 12
providers:
my_provider:
entity:
class: App\Entity\User
property: email
firewalls:
main:
anonymous: ~
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
provider: my_provider
stateless: true
lexik_jwt_authentication:
secret_key: '%env(APP_SECRET)%'
public_key: '%env(PUBLIC_KEY_PATH)%'
authentication_token_ttl: 86400
在config/routes.yaml中添加JWT路由:
api_login:
path: /api/login_check
methods: ['POST']
在User类中实现UserInterface接口:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
*/
class User implements UserInterface
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* @ORM\Column(type="json")
*/
private $roles = [];
/**
* @ORM\Column(type="string", length=100)
*/
private $password;
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
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;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getSalt()
{