在两个不同的前端和后端域名中使用Laravel Sanctum,您需要进行以下步骤:
composer require laravel/sanctum
config/auth.php
文件中,将 api
守卫的驱动程序更改为 sanctum
,如下所示:'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'sanctum',
'provider' => 'users',
'hash' => false,
],
],
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
fruitcake/laravel-cors
包,执行以下命令:composer require fruitcake/laravel-cors
然后,在 config/cors.php
文件中进行跨域配置,例如:
return [
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['https://frontend-domain.com', 'https://backend-domain.com'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
use Illuminate\Support\Facades\Http;
Route::get('/api/sanctum/csrf-cookie', function () {
return Http::get('https://backend-domain.com/sanctum/csrf-cookie');
});
Route::post('/api/login', function () {
$response = Http::post('https://backend-domain.com/login', [
'email' => 'email@example.com',
'password' => 'password',
]);
return $response->json();
});
在后端域名中的路由文件:
use App\Http\Controllers\AuthController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', [UserController::class, 'index']);
});
Route::post('/login', [AuthController::class, 'login']);
/api/sanctum/csrf-cookie
路由获取 CSRF 令牌,然后使用令牌进行登录请求,例如:fetch('https://frontend-domain.com/api/sanctum/csrf-cookie', {
credentials: 'include'
}).then(() => {
fetch('https://frontend-domain.com/api/login', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'email@example.com',
password: 'password',
}),
}).then(response => {
if (response.ok) {
// 登录成功
} else {
// 登录失败
}
});
});
EnsureFrontendRequestsAreStateful
中间件来验证请求是否来自前端域名,例如:namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function login(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required',
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return response()->json(['message' => 'Authenticated']);
}
return response()->json(['message' => 'Invalid credentials'], 401);
}
}
这样,您就可以在两个不同的前端和后端域名中成功使用 Laravel Sanctum 进行身份验证了。请注意,以上示例仅供参考,您可能需要根据自己的具体项目结构和需求进行适当的调整。
关于 Laravel Sanctum 的更多信息,您可以参考腾讯云提供的 Laravel Sanctum 的产品文档链接:Laravel Sanctum 产品文档
领取专属 10元无门槛券
手把手带您无忧上云