Laravel/Vue Passport(SPA)-将代币存储到cookies

Laravel/Vue Passport(SPA)-将代币存储到cookies,laravel,vue.js,single-page-application,laravel-passport,bearer-token,Laravel,Vue.js,Single Page Application,Laravel Passport,Bearer Token,我一直在学习一个关于Vue+Laravel身份验证的教程,所有内容都已设置好,但随后该教程介绍了如何在本地存储中存储令牌。我已经读到,这不是应该遵循的最佳实践,因为它更容易受到XSS攻击 问题是很难找到关于在cookie中存储令牌的教程(特别是Laravel+Vue)。任何人都可以帮助实现在cookie中存储令牌吗 非常感谢任何能帮忙的人 这是我目前的代码 控制器 public function login(Request $request) { $http = new\GuzzleH

我一直在学习一个关于Vue+Laravel身份验证的教程,所有内容都已设置好,但随后该教程介绍了如何在本地存储中存储令牌。我已经读到,这不是应该遵循的最佳实践,因为它更容易受到XSS攻击

问题是很难找到关于在cookie中存储令牌的教程(特别是Laravel+Vue)。任何人都可以帮助实现在cookie中存储令牌吗

非常感谢任何能帮忙的人

这是我目前的代码

控制器

public function login(Request $request) 
{
    $http = new\GuzzleHttp\Client;

    try {
        $response = $http->post(config('services.passport.login_endpoint'), [
            'form_params' => [
                'grant_type' => 'password',
                'client_id' => config('services.passport.client_id'),
                'client_secret' => config('services.passport.client_secret'),
                'username' => $request->username,
                'password' => $request->password,
            ]
        ]);
        return $response->getBody();
    } catch (\GuzzleHttp\Exception\BadResponseException $e) {
        if ($e->getCode() === 400) {
        return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
    } else if ($e->getCode() === 401) {
        return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
    }
        return response()->json('Something went wrong on the server.', $e->getCode());
    }
}

public function logout()
{
    auth()->user()->tokens->each(function ($token, $key) {
        $token->delete();
    });

    return response()->json('Logged out successfully', 200);
}
API路线

Route::post('/login', 'AuthController@login');
Route::middleware('auth:api')->post('/logout', 'AuthController@logout');
Vue组件脚本

<script>
  export default {
    props: {
      source: String,
    },
    data: () => ({
      username: '',
      password: '',
      valid: false,
    }),

    methods: {
      save() {
        const { username, password } = this
        axios 
        .post('api/login', { username, password })
        .then(response => console.log(response))
        .catch(error => console.log(error))
      }
    }
  }
</script>

导出默认值{
道具:{
资料来源:String,
},
数据:()=>({
用户名:“”,
密码:“”,
有效:假,
}),
方法:{
保存(){
const{username,password}=this
axios
.post('api/login',{username,password})
.then(response=>console.log(response))
.catch(错误=>console.log(错误))
}
}
}

使用
document.cookie=response.data.token
在cookie中存储令牌


导出默认值{
道具:{
资料来源:String,
},
数据:()=>({
用户名:“”,
密码:“”,
有效:假,
}),
方法:{
保存(){
const{username,password}=this
axios
.post('api/login',{username,password})
。然后(响应=>{
document.cookie=response.data.token
})
.catch(错误=>console.log(错误))
}
}
}

获取
cookie

var-token=document.cookie;

我认为最好的选择是使用
刷新令牌
(带有用户数据)作为服务器端cookie。并将
token
保存在vue存储中(您需要的
token
中的所有内容都是用户查看的用户数据)。此解决方案使XSS攻击变得不可能。这意味着服务器端cookie块javascript可以读取或写入此cookie。并且每次重新加载需要使用“自动登录”请求和
refresh\u token
cookie进行重新授权的页面(每次请求自动使用cookie),例如:

vue存储,例如“auth.ts”或“auth.js”

        /**
         * Autologin user.
         *
         * @param commit
         */
        async autologin({ commit }: any) {
            try {
                let { data } = await axios.post(`${endpoint}/${silentLogin}`)
                setExpiresDateToken(data.accessToken)

                commit('auth', {
                    token: data.accessToken,
                    idToken: data.idToken,
                })
            } catch (err) {
                localStorage.removeItem('expires')
                throw err
            }
        },
router.ts或router.js(I用户类型脚本)

/**
*检查用户访问是否允许。
*@param to
*@param from
*@param next
*@returns{Promise}
*/
const-authGuard=async(to:any、from:any、next:any)=>{
如果(!store.getters['auth/isAuth']){
试一试{
等待存储调度('auth/autologin'))
下一个()
}捕获(e){
下一步({name:'login'})
}
}否则{
下一个()
}
}
常数路由=[
{
路径:'/list',
名称:'列表',
组件:()=>导入('@/views/DocumentsList'),
输入前:authGuard,
}
]

如果你使用的是Laravel路由器,它可能是一种类似的方式

这太棒了!我有一个问题,在状态(vuex)中存储令牌是否与本地存储相同?或者,它和存储在cookie中一样好吗?@JimERussel我看到大多数ppl都使用本地存储,我也使用了本地存储,如果应用程序关闭,vuex您无法存储所有vuex数据,因此您需要一些存储来保存令牌,这是loaclstorage或Cookies非常感谢您的支持。我会试试这个。
/**
 * Check if user access allows.
 * @param to
 * @param from
 * @param next
 * @returns {Promise<void>}
 */
const authGuard = async (to: any, from: any, next: any) => {
    if (!store.getters['auth/isAuth']) {
        try {
            await store.dispatch('auth/autologin')
            next()
        } catch (e) {
            next({ name: 'login' })
        }
    } else {
        next()
    }
}

const routes = [
  {
    path: '/list',
    name: 'List',
    component: () => import('@/views/DocumentsList'),
    beforeEnter: authGuard,
  }
]