首页 > 解决方案 > 如何使用 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

标签: symfonyauthenticationgraphqllexikjwtauthbundle

解决方案


您可以实现自定义用户提供程序。例子:

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();

}
}

推荐阅读