簡體   English   中英

如何在 Symfony 6 使用 LexikJWTAuthenticationBundle 成功登錄后返回令牌和用戶

[英]How to return the token AND the user after successful login in Symfony 6 using LexikJWTAuthenticationBundle

我正在使用Symfony 6LexikJWTAuthenticationBundle 成功登錄后,我取回了一個令牌,但我也希望它能返回用戶。

這是我現在得到的回應:

$ curl -X POST -H "Content-Type: application/json" http://localhost/api/login_check -d '{"username":"martin","password":"123"}'

Response:
{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...."}

但我希望它像這樣在響應中包含經過身份驗證的用戶,但我無法在任何地方找到啟用它的方法。

{
  "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE2NDk4NjkxNzQsImV4cCI6MTY0OTg3Mjc3NCwicm9sZXMiOlsiUk9MRV9VU0VSIl0sInVzZXJuYW1lI....."
  "user": { id: 1, username: 'martin', password: '123' }
}

這是我的security.yaml的樣子:

security:
    enable_authenticator_manager: true
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
        App\Entity\User:
            algorithm: auto

    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\User
                property: username
    firewalls:
        login:
            pattern: ^/api/login
            stateless: true
            provider: app_user_provider
            json_login:
                check_path: /api/login_check
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure

        api:
            pattern: ^/api
            stateless: true
            jwt: ~

    access_control:
        - { path: ^/api/login,       roles: PUBLIC_ACCESS }
        - { path: ^/api,             roles: IS_AUTHENTICATED_FULLY }

when@test:
    security:
        password_hashers:
            Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
                algorithm: auto
                cost: 4 # Lowest possible value for bcrypt
                time_cost: 3 # Lowest possible value for argon
                memory_cost: 10 # Lowest possible value for argon

您需要實施自定義“success_handler”。

security:
  firewalls:
    login:
      json_login:
        success_handler: YOUR_CUSTOM_SUCCESS_HANDLER_SERVICE

最簡單的方法是擴展“Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Authentication\AuthenticationSuccessHandler”class 並覆蓋“handleAuthenticationSuccess”方法。

否則,如果您只需要更新響應數據:

監聽“Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent”並更新那里的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM