修改JWTRefreshTokenBundle的user_identity_field为email后刷新令牌401问题
/api/token/refresh After Switching Lexik JWT to Use Email as User Identity The Root Cause
When you set lexik_jwt_authentication.user_identity_field to email, you updated how Lexik JWT identifies users—but GesdinetJWTRefreshTokenBundle's default RefreshToken entity still stores the user's username instead of their email. This mismatch causes the refresh token validation to fail, throwing the 401 error.
Step-by-Step Solution
1. Create a Custom RefreshToken Entity
We need to override the default entity to store the user's email instead of username. Here's how:
// src/AppBundle/Entity/RefreshToken.php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Gesdinet\JWTRefreshTokenBundle\Entity\RefreshToken as BaseRefreshToken; /** * @ORM\Entity * @ORM\Table(name="refresh_tokens") */ class RefreshToken extends BaseRefreshToken { /** * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * @ORM\Column(type="integer") */ protected $id; /** * @ORM\Column(type="string", length=255) */ protected $email; // Replace the original `username` field // Override setUser to store the user's email public function setUser($user) { $this->email = $user->getEmail(); return $this; } // Override getUser to return the email for validation public function getUser() { return $this->email; } }
2. Update Gesdinet Bundle Configuration
Tell the bundle to use your custom entity in config.yml:
gesdinet_jwt_refresh_token: ttl: '%jwt_refresh_token_ttl%' ttl_update: true user_provider: security.user.provider.concrete.chain_provider refresh_token_class: AppBundle\Entity\RefreshToken # Add this line to specify your custom entity
3. Update Your Database
Since we modified the entity structure, generate and run a Doctrine migration to update the refresh_tokens table:
# Generate a migration file php bin/console doctrine:migrations:generate # Execute the migration to apply changes php bin/console doctrine:migrations:migrate
4. Double-Check Login Logic
If you're using a custom login success handler (your custom handler), ensure it passes the user's email when generating the refresh token. If you're using the default logic, our overridden setUser method will handle this automatically—no extra work needed here.
Verify the Fix
Log in again to get a new access and refresh token. Now the refresh token's email field will hold the user's email address. When you call /api/token/refresh, the bundle will use this email to look up the user, and you'll get a valid new access token instead of the 401 error.
内容的提问来源于stack exchange,提问作者shuba.ivan

