我正在使用
Laravel Passport
构建 API,我相应地删除了网络路由及其防护
如何测试用户注销?
这是我到目前为止所拥有的:
Logout Test
/**
* Assert users can logout
*
* @return void
*/
public function test_logout()
{
// $data->token_type = "Bearer"
// $data->access_token = "Long string that is a valid token stripped out for brevety"
$response = $this->json('POST', '/api/logout', [], [
'Authorization' => $data->token_type . ' ' . $data->access_token
]);
$response->assertStatus(200);
}
routes/api.php
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
AuthenticatesUsers
特性,因此保留默认功能/**
* Log the user out of the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return $this->loggedOut($request) ?: redirect('/');
}
错误方法 Illuminate\Auth\RequestGuard::logout 不存在
Laravel 文档讨论了颁发和刷新访问令牌,但没有提到撤销它们或执行注销
public function logout(Request $request)
{
$request->user()->token()->revoke();
return $this->loggedOut($request);
}
Test Fails on second assertion
public function test_logout()
{
$response = $this->json('POST', '/api/logout', [], [
'Authorization' => $data->token_type . ' ' . $data->access_token
]);
$response->assertStatus(200); // Passes
$check_request = $this->get('/api/user');
$check_request->assertForbidden(); // Fails
}
假设默认路由需要身份验证
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
响应状态码[200]不是禁止状态码。
所以这是怎么回事?如何使用 Passport 测试用户注销?
撤销令牌正在起作用。这是测试不起作用,但原因尚不清楚。
在一次测试中发出多个请求时,laravel 应用程序的状态不会在请求之间重置。 Auth 管理器是 Laravel 容器中的一个单例,它保留已解析的 Auth Guard 的本地缓存。已解析的身份验证守卫会保留经过身份验证的用户的本地缓存。
因此,您对
api/logout
端点的第一个请求会解析身份验证管理器,从而解析 api 防护,后者存储对您将撤销其令牌的经过身份验证的用户的引用。
现在,当您向
/api/user
发出第二个请求时,将从容器中提取已解析的身份验证管理器,从其本地缓存中提取已解析的 api 防护,并从防护的本地缓存中提取相同的已解析用户。这就是第二个请求通过身份验证而不是失败的原因。
在同一测试中使用多个请求测试与身份验证相关的内容时,您需要在测试之间重置已解析的实例。另外,您不能只取消设置已解析的身份验证管理器实例,因为当再次解析它时,它不会定义扩展的
passport
驱动程序。
因此,我发现的最简单的方法是使用反射来取消设置已解析的身份验证管理器上受保护的
guards
属性。您还需要在已解析的会话防护上调用 logout
方法。
我的 TestCase 类上有一个方法,如下所示:
protected function resetAuth(array $guards = null)
{
$guards = $guards ?: array_keys(config('auth.guards'));
foreach ($guards as $guard) {
$guard = $this->app['auth']->guard($guard);
if ($guard instanceof \Illuminate\Auth\SessionGuard) {
$guard->logout();
}
}
$protectedProperty = new \ReflectionProperty($this->app['auth'], 'guards');
$protectedProperty->setAccessible(true);
$protectedProperty->setValue($this->app['auth'], []);
}
现在,您的测试将类似于:
public function test_logout()
{
$response = $this->json('POST', '/api/logout', [], [
'Authorization' => $data->token_type . ' ' . $data->access_token
]);
$response->assertStatus(200);
// Directly assert the api user's token was revoked.
$this->assertTrue($this->app['auth']->guard('api')->user()->token()->revoked);
$this->resetAuth();
// Assert using the revoked token for the next request won't work.
$response = $this->json('GET', '/api/user', [], [
'Authorization' => $data->token_type . ' ' . $data->access_token
]);
$response->assertStatus(401);
}
auth()->guard('web')->logout()
使用
auth()->guard('web')->logout()
和auth()->guard('web')->login($user)
解决了我的问题,在官方文档中找到误导性的步骤真的很奇怪。
用途:
auth()->forgetGuards();
接受的答案对我不起作用。我终于注意到,当撤销用户令牌并从接受的答案中调用 ResetAuth() 时,它起作用了:
protected function resetAuth() {
$this->app['auth']->guard('api')->user()->token()->revoke(); //Revoke (or delete()) the passport user token.
//$this->app['auth']->guard('web')->logout(); //If you also want to call the logout function on your web guard.
$protectedProperty = new \ReflectionProperty($this->app['auth'], 'guards');
$protectedProperty->setAccessible(true);
$protectedProperty->setValue($this->app['auth'], []);
}
但是在使用 $this->isAuthenticated() 等方法时会抛出异常 -
//League\OAuth2\Server\Exception\OAuthServerException: The resource owner or authorization server denied the request.
我最终发现:
auth()->forgetGuards();
这似乎可以正确清除身份验证,而不会出现任何后续问题。
此代码对我有用:
// UserController.php
public function deactivateUser(Request $request): RedirectResponse {
$user = Auth::user();
if ($user->status === 'active') {
$user->status = 'inactive';
$user->save();
if (Auth::check()) {
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
}
}
return redirect()->route('login')->with('success', 'Logout successfully' );
}