验证令牌是令牌 Laravel 护照

Verify Token is Token Laravel Passport

我最近从 laravel 的 sanctum 更新到护照;有一个测试让我很困扰。 在 sanctum 中,PersonalAccessToken 模型下有这个方法可以找到令牌,returns 令牌(如果存在)。 我似乎没有在文档或网上找到类似的东西。 我通过断言 $user->tokens 不为空来验证测试...但我希望验证我从登录控制器返回的令牌确实是一个令牌;不只是创作;

提前致谢...

登录测试

public function user_can_login()
{
    //$this->withoutExceptionHandling();

    $user = User::factory()->create();
    $url = route('api.v1.auth.login', [
        'email' => $user->email,
        'password' => 'password'
    ]);
    $res = $this->jsonApi()
        ->post($url)
        ->assertStatus(200);

    $token = $res->json(['access_token']);

    $this->assertNotEmpty($user->tokens);
}

authcontroller中的登录方法

public function login(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    $credentials = $request->only(['email', 'password']);

    if (Auth::attempt($credentials)) {
        $user = Auth::user();
        $access_token = $user->createToken('laravel-api.local')->accessToken;
        return response()->json(['access_token' => $access_token], 200);
    } else {
        return response()->json(['error' => 'Unauthorized'], 401);
    }
}

pues: 不知道我为什么要写代码,但只是为了参考我在做什么

https://laracasts.com/discuss/channels/testing/how-do-i-create-a-route-while-testing

解决方案非常简单......你会在这里找到它......我之前尝试过这个问题时遇到了问题,它似乎与使用 Route::name('name') 方法和 route('name') 函数引发了服务器错误。但是如果你直接调用路径它应该工作...

任何人……authController 和登录方法保持不变,但测试更改为……

public function setUp(): void
{
    parent::setUp();

    Route::middleware('auth:api')
        ->get('/test-route', function (Request $request) {
            return $request->user();
        });

    $clientRepository = new ClientRepository();

    $client = $clientRepository->createPersonalAccessClient(
        null,
        'Personal Access Client Test',
        '/'
    );
    DB::table('oauth_personal_access_clients')->insert([
        'client_id' => $client->id,
        'created_at' => date('Y-m-d'),
        'updated_at' => date('Y-m-d'),
    ]);
}

/** @test */
public function user_can_login_with_correct_credentials()
{
    //$this->withoutExceptionHandling();

    $user = User::factory()->create();
    $url = route('api.v1.auth.login', [
        'email' => $user->email,
        'password' => 'password',
        'device_name' => $user->name . ' test Device'
    ]);
    $res = $this->jsonApi()
        ->post($url)
        ->assertStatus(200);

    $token = $res->json(['access_token']);

    $this->jsonApi()
        ->withHeader('Authorization', 'Bearer ' . $token)
        ->get('/test-route')
        ->assertStatus(200);
}