如何使用JWT令牌配置多个用户实体?

时间:2020-04-08 13:22:57

标签: php symfony symfony4 symfony-security lexikjwtauthbundle

我有多个用户实体(多个表):

  1. App \ Entity \ Customer

  2. App \ Entity \ Dealer

如何使用JWT令牌配置多个用户实体?

encoders:
    App\Entity\Dealer:
        algorithm: bcrypt

    App\Entity\Customer:
        algorithm: bcrypt

providers:
    dealer:
        entity:
          class: App\Entity\Dealer
          property: username

    customer:
        entity:
            class: App\Entity\Customer
            property: username

1 个答案:

答案 0 :(得分:1)

没有JWT专门用于拥有多个用户提供程序。

如果两种类型的用户都需要登录相同的防火墙(例如,相同的URL模式),则需要创建一个链用户提供程序,以便系统尝试从每个用户提供程序中获取用户。 :

providers:
    ## ... your other providers up here.
    all_users:
          chain:
            providers: ['customer', 'dealer']

您将需要在要保护的防火墙中使用此提供程序:

firewall:
    ## ... other firewall entries ...
    api:
      pattern:   ^/api
      stateless: true
      anonymous: true
      provider: all_users
      guard:
        authenticators:
          - lexik_jwt_authentication.jwt_token_authenticator

对于每种类型的用户,您还应该具有单独的登录路径,每个登录路径都有其自己的特定用户提供程序:

firewall:
###
    customer_login:
      pattern:  ^/auth/login/customer
      stateless: true
      anonymous: true
      provider: customer
      json_login:
        check_path: /auth/login/customer
        success_handler: lexik_jwt_authentication.handler.authentication_success
        failure_handler: lexik_jwt_authentication.handler.authentication_failure

    dealer_login:
      pattern: ^/auth/login/dealer
      stateless: true
      anonymous: true
      provider: dealer
      json_login:
        check_path: /auth/login/dealer
        success_handler: lexik_jwt_authentication.handler.authentication_success
        failure_handler: lexik_jwt_authentication.handler.authentication_failure

现在,您的“交易者”在/auth/login/dealer获得令牌,而您的“客户”在/auth/login/customer获得令牌。

由于要依次检查经销商和客户的提供商,因此如果两个表中的用户名都相同,则可能会出现问题(因为只有在未找到第二个提供商的情况下才检查第二个提供商)第一个),因此您应该进行相应的计划。