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

问题描述 投票:1回答:1

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

  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

php symfony symfony4 symfony-security lexikjwtauthbundle
1个回答
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处获得其令牌。

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

© www.soinside.com 2019 - 2024. All rights reserved.