我在Laravel Sanctum遇到此错误。我通过将其添加\Illuminate\Session\Middleware\StartSession::class,
到api
Kernel.php 的中间件组中来对其进行了修复,但是后来我发现这是“可行的”,因为添加了我的身份验证路由api.php
而不是web.php
,因此Laravel使用了错误的身份验证保护。
我将这些路线移至此处web.php
,然后它们开始使用该AuthenticatesUsers.php
特征正常工作:
Route::group(['middleware' => ['guest', 'throttle:10,5']], function () {
Route::post('register', 'Auth\RegisterController@register')->name('register');
Route::post('login', 'Auth\LoginController@login')->name('login');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');
Route::post('email/verify/{user}', 'Auth\VerificationController@verify')->name('verification.verify');
Route::post('email/resend', 'Auth\VerificationController@resend');
Route::post('oauth/{driver}', 'Auth\OAuthController@redirectToProvider')->name('oauth.redirect');
Route::get('oauth/{driver}/callback', 'Auth\OAuthController@handleProviderCallback')->name('oauth.callback');
});
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
在发现另一个奇怪的错误后,我发现了问题RequestGuard::logout()
。
这让我意识到我的自定义身份验证路由正在从AuthenticatesUsers特性调用方法,但是我并没有用Auth::routes()
它来实现它。然后我意识到Laravel默认使用web防护,这意味着路由应该在routes/web.php
。
这是我现在使用Sanctum和解耦的Vue SPA应用程序时的设置:
内核.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
'throttle:60,1',
],
];
注意:使用Laravel Sanctum和同域Vue SPA,您将httpOnly cookie用于会话cookie,并记住我cookie和针对CSRF的不安全cookie,因此您将web
保护用于auth,并且应使用所有其他受保护的JSON返回路由auth:sanctum
中间件。
config / auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
...
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
然后你就可以有单元测试,像这样的,其中关键的是,Auth::check()
,Auth::user()
,和Auth::logout()
按预期方式工作以最小的配置和最大使用量AuthenticatesUsers
和RegistersUsers
性状。
这是我的一些登录单元测试:
TestCase.php
/**
* Creates and/or returns the designated regular user for unit testing
*
* @return \App\User
*/
public function user() : User
{
$user = User::query()->firstWhere('email', 'test-user@example.com');
if ($user) {
return $user;
}
// User::generate() is just a wrapper around User::create()
$user = User::generate('Test User', 'test-user@example.com', self::AUTH_PASSWORD);
return $user;
}
/**
* Resets AuthManager state by logging out the user from all auth guards.
* This is used between unit tests to wipe cached auth state.
*
* @param array $guards
* @return void
*/
protected function resetAuth(array $guards = null) : void
{
$guards = $guards ?: array_keys(config('auth.guards'));
foreach ($guards as $guard) {
$guard = $this->app['auth']->guard($guard);
if ($guard instanceof SessionGuard) {
$guard->logout();
}
}
$protectedProperty = new \ReflectionProperty($this->app['auth'], 'guards');
$protectedProperty->setAccessible(true);
$protectedProperty->setValue($this->app['auth'], []);
}
LoginTest.php
protected $auth_guard = 'web';
/** @test */
public function it_can_login()
{
$user = $this->user();
$this->postJson(route('login'), ['email' => $user->email, 'password' => TestCase::AUTH_PASSWORD])
->assertStatus(200)
->assertJsonStructure([
'user' => [
...expectedUserFields,
],
]);
$this->assertEquals(Auth::check(), true);
$this->assertEquals(Auth::user()->email, $user->email);
$this->assertAuthenticated($this->auth_guard);
$this->assertAuthenticatedAs($user, $this->auth_guard);
$this->resetAuth();
}
/** @test */
public function it_can_logout()
{
$this->actingAs($this->user())
->postJson(route('logout'))
->assertStatus(204);
$this->assertGuest($this->auth_guard);
$this->resetAuth();
}
我在Laravel auth特性中重写了registered
and authenticated
方法,以便它们返回用户对象,而不仅仅是204个OPTIONS:
public function authenticated(Request $request, User $user)
{
return response()->json([
'user' => $user,
]);
}
protected function registered(Request $request, User $user)
{
return response()->json([
'user' => $user,
]);
}
查看供应商代码以获取auth特性。您可以原封不动地使用它们,以及上面的两种方法。
- 供应商/laravel/ui/auth-backend/RegistersUsers.php
- 供应商/laravel/ui/auth-backend/AuthenticatesUsers.php
这是我的Vue SPA的Vuex登录操作:
async login({ commit }, credentials) {
try {
const { data } = await axios.post(route('login'), {
...credentials,
remember: credentials.remember || undefined,
});
commit(FETCH_USER_SUCCESS, { user: data.user });
commit(LOGIN);
return commit(CLEAR_INTENDED_URL);
} catch (err) {
commit(LOGOUT);
throw new Error(`auth/login# Problem logging user in: ${err}.`);
}
},
async logout({ commit }) {
try {
await axios.post(route('logout'));
return commit(LOGOUT);
} catch (err) {
commit(LOGOUT);
throw new Error(`auth/logout# Problem logging user out: ${err}.`);
}
},
我花了一个多星期的时间才能获得Laravel Sanctum +同域Vue SPA +身份验证单元测试,所有测试都达到了我的标准,因此希望我在这里得到的答案可以帮助将来节省其他人的时间。