【问题标题】:Laravel REST Api not sending cookies to different domain?Laravel REST Api 没有将 cookie 发送到不同的域?
【发布时间】:2019-08-23 03:46:51
【问题描述】:

我想通过我的 Laravel Rest API 将我的身份验证服务(Passport)中的仅 http cookie 发送到位于世界任何地方的消费前端。但是,没有 cookie 被发送到前端。

我尝试使用 withCookie() 和 cookie() 设置带有 json 响应的 cookie。那没有用。

这位于 kernel.php 中,Laravel Passport 文档(Consuming Your API with Javascript 部分),但是,它不会随响应一起发送。

'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

这不会发送 cookie

public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
            'remember_me' => 'boolean'
        ]);
        $credentials = request(['email', 'password']);
        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
        $user = $request->user();
        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;
        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);
        $token->save();


         return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
        ]);

    }

我希望它发送带有令牌的 http cookie,但是它不起作用。

【问题讨论】:

  • 您不能为其他域设置 cookie。 Passport 使用 API 令牌,而不是 cookie。
  • 是的,但我想将其存储在仅 http 的 cookie 中。我不知道还有其他安全方法吗?
  • 客户端使用您的 API 将负责以某种方式存储令牌。

标签: php laravel rest api cookies


【解决方案1】:

浏览器不接受存储或读取其他域的cookies。

注意:domain.tld 可以访问 sub.domain.tld 的 cookie,但反之则不行。

【讨论】:

  • 那我该怎么做呢?
  • 在同一个域中使用 cookie。否则你不能这样做。
  • 这有什么意义? Laravel Docs 明确表示这是一种可接受的行为,它会在我的传出响应中发送一个 laravel_token cookie。
  • 是的,但是浏览器不会将该 cookie 发送到不同域的网站,因此它不会知道会话。让您的应用程序在同一个域上运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 2012-10-08
  • 2015-04-04
  • 2020-07-07
  • 2011-03-15
  • 1970-01-01
  • 2020-03-12
相关资源
最近更新 更多