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

Symfony3.3中LexikJWTAuthenticationBundle单元测试Token无效报错

Hey there! Let's break down why your test case is throwing that 401 error even though curl works fine. I've run into similar issues with LexikJWT in Symfony tests before, so here are the most likely fixes to try:

1. Make sure you're correctly fetching and attaching the JWT token in your test

When you use curl, you probably first hit /login_check to get a token, then attach it to your API request. Your test needs to do the exact same thing—don't hardcode a token from your local dev environment, because it might expire or not match the test environment's keys.

Here's how to implement that in your test:

public function testPOSTRate()
{
    // First, send a request to /login_check to get a valid token
    $loginResponse = $this->client->request('POST', '/login_check', [
        'json' => [
            'username' => 'your-test-user-username',
            'password' => 'your-test-user-password',
        ],
    ]);

    $tokenData = json_decode($loginResponse->getContent(), true);
    $jwtToken = $tokenData['token'];

    // Now use this token in your API request
    $this->client->request('GET', '/api/stores', [
        'headers' => [
            'Authorization' => sprintf('Bearer %s', $jwtToken),
            'Content-Type' => 'application/json',
        ],
    ]);

    // Assert the response is successful
    $this->assertResponseIsSuccessful();
}

Pro tip: If you're reusing this token logic across multiple tests, extract it into a helper method (like getValidJwtToken()) to keep your code clean.

2. Verify your test environment uses the correct JWT keys

LexikJWT relies on public/private key pairs to sign and validate tokens. If your test environment is using different keys than your local dev environment (where you ran curl), tokens generated in dev won't work in tests.

Check your config/packages/test/lexik_jwt_authentication.yaml file—make sure the public_key_path and private_key_path point to valid files, and that these keys are the ones used when generating tokens in your test. If you don't have a test-specific config, it will fall back to the dev config, but double-check the paths are correct for your test setup.

3. Ensure the token isn't expiring mid-test

By default, LexikJWT tokens expire after 1 hour, but if you've modified the token_ttl in your config, it might be shorter. If your test suite runs slowly, the token could expire before you use it. To fix this, either:

  • Increase the token_ttl in your test config (e.g., set it to 36000 for 10 hours)
  • Generate the token right before making the API request (like in the example above) instead of generating it once at the start of the test class.

4. Check that your test client is sending the headers correctly

Sometimes, the Symfony test client can be finicky with headers. Make sure you're using the headers array correctly in the request() method, and that you're setting Content-Type: application/json if your API expects JSON requests. Also, double-check that the Authorization header is spelled correctly (no typos like Autorization!)

5. Validate the token directly to debug

If you're still stuck, take the token generated in your test and validate it manually to see what's wrong. You can use the lexik:jwt:decode command in your test environment:

bin/console lexik:jwt:decode your-token-string --env=test

This will show you if the token is expired, has invalid claims, or was signed with the wrong key.

Once you work through these steps, your test should start working just like your curl requests do!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:40:31