symfony - 如何使用 symfony5 的 LexikJWT 捆绑包通过用户名或电子邮件登录?
问题描述
我正在为我的 symfony5 API 使用 LexikJWT 和 GraphQL,但我不知道如何配置我的应用程序以通过用户名或电子邮件登录。
这是我的 security.yaml 和 lexik_jwt_authentication.yaml
// 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
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
stateless: true
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
// 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)%'
token_ttl: 604800
user_identity_field: username
解决方案
您可以实现自定义用户提供程序。例子:
class UserRepository extends ServiceEntityRepository implements UserLoaderInterface
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, User::class);
}
/**
* Loads the user for the given username.
*
* This method must return null if the user is not found.
*
* @param $usernameOrEmail
* @return UserInterface|null
* @throws \Doctrine\ORM\NonUniqueResultException
*/
public function loadUserByUsername($usernameOrEmail)
{
return $this->createQueryBuilder('u')
->where('u.username = :query OR u.email = :query')
->setParameter('query', $usernameOrEmail)
->getQuery()
->getOneOrNullResult();
}
}
推荐阅读
- docker - 构建“无法在节点上执行操作”时出现 Docker rabbitmq 映像错误
- javascript - 即使给出了必填字段,也会发生猫鼬验证错误
- javascript - 在反应中将键排序到地图中
- r - read.table 中的错误(file = file,header = header,sep = sep,quote = quote,:不允许重复的'row.names'
- amazon-web-services - 我无法将我的 json 发布到我的 api lambda 函数。我收到 {"message":"Missing Authentication Token"}
- c# - 组合框 tostring() 返回对象而不是值
- excel - 如何在 matlab 中使用 writetable 函数擦除 Sheet1 Sheet2 和 Sheet3?
- javascript - 通过 javascript 读取 JSON 文件
- python - 查找两条线之间的点
- css - 如何在 cdk-virtual-scroll-viewport 填充其余高度时始终保持工具栏位于顶部?