Symfony中从HTTP请求获取JWT字符串并解码的方法及问题求助
Hey there! As a fellow Symfony developer working with JWT, I noticed a key issue in your code—you're trying to use TokenStorageInterface with a raw JWT string, which isn't what that service is designed for. Let's fix this and walk through the correct approach.
What's Wrong with Your Current Code?
The TokenStorageInterface is meant to store Symfony's native TokenInterface objects (like the ones generated after successful authentication), not raw JWT strings. Passing a plain string to setToken() will cause errors because it expects a token object, not text.
Correct Approach to Decode a Raw JWT
Assuming you're using the LexikJWTAuthenticationBundle (the standard for JWT in Symfony), here's how to properly decode your JWT string:
Step 1: Skip TokenStorage (You Don't Need It Here)
You can directly pass the raw JWT string to the jwtManager->decode() method—no need to involve TokenStorage for this use case.
Step 2: Handle Validation & Exceptions
The decode() method will automatically validate the token's signature, expiration time, and other claims. You should wrap this in a try-catch block to handle invalid tokens gracefully.
Corrected Code Example
use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTDecodeFailureException; // Your raw JWT string from the POST request $post_data = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE2NjE3NzUwMDAsImV4cCI6MTY2MTc3ODYwMCwicm9sZXMiOlsiUk9MRV9VU0VSIl0sInVzZXJuYW1lIjoibGVmb3J0LmF1Z3VzdGVAZ2ltZW5lei5mciJ9.btG_nhid4qmDa3xMkjybZb7v8T49e3SLoWHlML8yCXizdC0GY1dDr1sli8zwPJGfjaATxGmq4tMSCxAG7pXwSwtb_KMtg54cf8IZULEIBHhpkgiObXWwZ9BwQFc3_KCFOnXhKft6mIljROrDv0VKUxG7UhCCwfPaAA2goQNqpeYTP0Zo0s6QGZ2UZ03vUGnZuSoqmRwIQ_23_q6E9BW-1fVjDHCyGBzxgSObfkDB27f_DbJA-GWejTj_15d1ZFHcPF30O8QkNN0IS4pw4LhWa6LGUO0pWKVl96oOSQ0PV6F1KpjkCbTX6x3rdTY3p_btyFT5gxgzfF4lx2sMRWJtmeWvmKhO22IVsxcGpqEm-XF-NrWSA7BNLzVXgWA3H8E6f7ienSWiVoqxV8sGodHygn8as7mGaUmwgKJ-o3xQ6E99zFFFduatJYORV3mdmASbVbIcLqoGISBDQ1bSl_UkCppVrG_xpIlYyoTTINbi68VSqPZwfQHTcQy8ZZmvls_ipxzB7VSXSRmDJQIN4_rkn8N7UF1eVBP_Vhoy5qtnZACLuk6RHB4Hww_5Hfbb46vHtijfcPxplhRSqJqlki0zIeJk3YltCQ7I98cn6XCVfVKr-Tzmmb_cGKS8qv9R13PZQmSbwPbtHQGUltcbgafbAgypgkp53znfy_DiCS_sWxA"; try { // Directly decode the raw JWT string $decodedJwtToken = $this->jwtManager->decode($post_data); // $decodedJwtToken will be an array with your claims (like roles, username, exp, etc.) return $this->render('jwt/index.html.twig', [ 'decodedJwtToken' => $decodedJwtToken, ]); } catch (JWTDecodeFailureException $e) { // Handle invalid token cases (expired, bad signature, etc.) return $this->json([ 'error' => 'Invalid JWT token', 'message' => $e->getMessage() ], 400); }
Additional Notes
- Ensure Bundle Configuration: Double-check that your LexikJWTAuthenticationBundle is properly configured with the correct public/private keys in your
config/packages/lexik_jwt_authentication.yaml. - Token Claims: The decoded array will contain all the claims from your JWT—you can access them directly like
$decodedJwtToken['username']or$decodedJwtToken['roles']. - Security Considerations: Never trust raw JWT strings without validating them. The
decode()method handles this for you, so always use it instead of manual decoding (like base64 decoding the payload directly).
内容的提问来源于stack exchange,提问作者Badreddine Barradi

