我想在laravel sanctum的SPA中进行身份验证。然后我像下面的代码一样设置环境。但是,在我登录并下一个api请求后,发生了错误。为什么?。第一个请求返回X-CSRF-TOKEN。据我所知,axios登录后会自动提交X-CSRF-TOKEN。请给我建议。
api.php
Route::middleware('auth:sanctum')->get('/sanctum/test', function (Request $request) {
return 'Nice!';
});
Route::post('/login', 'Auth\LoginController@login');
LoginController的登录方法
public function login(Request $request)
{
$this->validateLogin($request);
$user = User::where('number', $request->login_id)->orWhere('email', $request->login_id)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'login_id' => ['uncorrect'],
]);
} else {
return 'success';
}
}
Sign_in.tsx
function Submit() {
axios.get('/sanctum/csrf-cookie').then(response => {
console.log(response);
axios
.post("/api/login", {
login_id: loginID,
password: password,
})
.then(response => {
console.log(response);
axios.get('/api/sanctum/test').then(res => {
console.log(res);
})
})
});
}
Karnel.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,
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
database.php
APP_NAME=Laravel
APP_ENV=local
APP_KEY=secret
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=secret
DB_USERNAME=root
DB_PASSWORD=secret
SESSION_DRIVER=file
SANCTUM_STATEFUL_DOMAINS=localhost:8000
SESSION_DOMAIN=localhost
答案 0 :(得分:0)
在Route::middleware('auth:sanctum')
中需要Authorization:<Bearer-Token>
标头。为连续的请求设置Authorization
标头即可。