You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改LexikJWTAuthenticationBundle默认用户名字段适配Symfony升级

适配LexikJWTAuthenticationBundle兼容旧版_username字段(Symfony5.4升级)

要让Symfony5.4版本的LexikJWTAuthenticationBundle兼容旧版的_username字段(替代默认的username),只需在security.yaml的登录防火墙配置中,给form_login添加字段名覆盖参数即可:

修改后的security.yaml配置

firewalls:
    login:
        pattern:  ^/api/login
        stateless: true
        anonymous: true
        form_login:
            check_path:               /api/login_check
            success_handler:          lexik_jwt_authentication.handler.authentication_success
            failure_handler:          lexik_jwt_authentication.handler.authentication_failure
            require_previous_session: false
            # 添加以下两行,覆盖默认字段名
            username_parameter: "_username"
            password_parameter: "_password"

    refresh:
        pattern:  ^/api/token/refresh
        stateless: true
        anonymous: true

    api:
        pattern:   ^/api/secure
        stateless: true
        guard:
            authenticators:
                - word.user.guard.jwt_token_authenticator

    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_token_generator: security.csrf.token_manager
        logout:       true
        anonymous:    true

说明

Symfony5.4中,LexikJWT的登录认证依赖Symfony原生的form_login组件,该组件默认使用username和password作为请求字段名。通过配置username_parameter和password_parameter,可以强制指定为旧版本使用的_username和_password,从而实现新旧客户端的兼容,无需修改原有API调用逻辑。

内容的提问来源于stack exchange,提问作者oracle972

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 17:01:05