我有一个使用 Laravel REST API 的移动应用程序。此应用程序中的授权使用 Laravel Sanctum 包。这种架构效果很好,但我不仅需要创建一个移动应用程序,还需要创建一个网站。由于我在网站的某些页面上有复杂的业务逻辑,因此我无法使用纯 PHP,我必须使用 javascript 和 Vue 等框架。已经有一个用于处理数据的 REST API,但问题是授权。关于安全性的问题,这种方法的正确性如何,以及是否可以混合使用 Laravel Breeze
auth 和 Laravel Sanctum
。我的想法是,在注册用户时,我还会为他创建一个访问 token ,但不将其存储在客户端浏览器上,而是通过 View 传递。由于我是 Laravel 架构的新手,也许这个问题有更好的解决方案?
//controller
use Illuminate\Support\Facades\Auth;
if (Auth::check()) {
$url = "/api/product/url-for-auth-user"
$token = $userAccessTokenFromDb;
}else{
$url = "/api/product/url-for-anonymous-user";
$token = "";
}
//blade webpage
<div id="app">
<div>
//Vue component to which the link to REST API and token are passed
<product url="{{$url}}" token="{{$token}}"></product>
</div>
</div>
最佳答案
如果您使用预期的功能,在 Breeze 的路由中使用 web.php 和 api.php,一切都会很好。当您使用 api 登录用户时,也会设置 session cookie,反之亦然。我已经远离微风有一段时间了,它不使用像 JetStream 这样的 Sanctum 吗?无论如何,JetSream 确实使用了 sainttum:
Middlewares = [
'auth:sanctum',
config('jetstream.auth_session'),//which is AuthenticateSession::class
]
您在 config/auth.php 中为 Web 和 api 设置不同的守则 返回[
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
在 config/sanctup 中,您可以将该 Web gaurd 定义为默认值:
'guard' => ['web'],
这一切都应该已经为您设置好了! 然后你可以只使用 web.php 中的中间件用于使用 sainttum 的 web,并且routes/api.php应该用于路由,这就是你定义授权路由的地方:
//路由/web.php 路线::中间件([ '授权: Sanctuary ', ])->组(函数(){
//protected routes
});
//api.php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
breaze 已经在 web.php 中创建了这个,这一切都可以以最小的努力开箱即用,我想不出如果你做得正确,需要手动设置什么,我认为你只需要使用路由分离并使用中间件,并根据 laravel 安装文档首先安装 sainttum 和 Breeze。
关于Laravel Breeze 和 Laravel Sanctum 如何安全地混合授权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73289994/