无法为API路线Laravel设置Cookie

无法为API路线Laravel设置Cookie

本文介绍了无法为API路线Laravel设置Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用后端(laravel)和前端SPA(vue.js,vue-cli 3)进行服务.我需要通过httpOnly cookie(而不是localStorage)进行身份验证.我使用 tymondesigns/jwt-auth 作为api身份验证包.

Doing an service with backend (laravel) and frontend SPA (vue.js, vue-cli 3). I need to make an auth via httpOnly cookie (not localStorage). I use tymondesigns/jwt-auth as api auth package.

我的环境是:

  • API路由: http://brideplanner.test/api
  • SPA路线: http://app-test.brideplanner.test:81/

我的登录路径为/api/auth/login ,控制器方法为:

My login route is /api/auth/login, controller method is:

public function login()
    {
        $credentials = request(['email', 'password']);
        $user = User::where('email','=',$credentials['email'])->first();
        if (!$user || !$token = auth()->claims(['sub' => $user->id, 'csrf-token' => str_random(32) ])->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        return response()
            ->json('success')
            ->withCookie('token', $token, config('jwt.ttl'), ".brideplanner.test", null, false, false);
    }

但是当我尝试向API发送请求时,cookie存储中没有 token 项.怎么了为什么没有令牌?我该怎么办?

But when I try to send an request to the API, there's no token item in the cookie storage. What's wrong here? Why there's no token? What should I do?

UPD:我通过邮递员测试了请求,并获得了令牌:

UPD: I tested the request via postman and I got the token:

的Set-Cookie→标记= eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9icmlkZXBsYW5uZXIudGVzdFwvYXBpXC9hdXRoXC9sb2dpbiIsImlhdCI6MTU1MTM5NDMwNCwiZXhwIjoxNTUxMzk1MjA0LCJuYmYiOjE1NTEzOTQzMDQsImp0aSI6Im9uU1NtWEpSU0prR3NKc3giLCJzdWIiOjEsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEiLCIwIjoic3ViIiwiMSI6ImNzcmYtdG9rZW4iLCJjc3JmLXRva2VuIjoiTE9jSDFCWG9ITFJBMjlFYTg2MG1XQXhrVnpTR2gzT2oifQ.mnR4C6bwMIVptU64eZ6tN-gCYyFEuCIk_dm6dJsXrLY;expires =星期四,2019年2月28日23:06:44 GMT;最大年龄= 900;path = .brideplanner.test;domain = .brideplanner.test;httponly

但是,当我从我的SPA( http://app-test.brideplanner.test:81/)发送请求时,它就出错了.

But when I send the request from my SPA (http://app-test.brideplanner.test:81/), it goes wrong.

推荐答案

在默认的Laravel安装中, api 路由不要启用用于处理cookie的中间件( Illuminate \ Cookie \ Middleware \ AddQueuedCookiesToResponse ).

In a default Laravel install, the api routes do not have the middleware (Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse) enabled that handles cookies.

如果确实需要基于cookie的身份验证,则可以在API路由上启用此中间件,但请务必在 差异.

You can enable this middleware on your API routes, if you really need cookie-based auth, but be sure to read up on the differences.

这篇关于无法为API路线Laravel设置Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 17:25