Laravel / Vue Passport(SPA)-将令牌存储到cookie

时间:2020-01-03 10:37:48

标签: laravel vue.js single-page-application laravel-passport bearer-token

我一直在关注有关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>

2 个答案:

答案 0 :(得分:2)

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

<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 => {
           document.cookie =  response.data.token
             })
        .catch(error => console.log(error))
      }
    }
  }
</script>

https://www.w3schools.com/js/js_cookies.asp

获得cookie

var token = document.cookie;

答案 1 :(得分:2)

我认为最好的选择是将refresh_token(带有用户数据)用作服务器端cookie。并将token保存在vue存储中(token所需的一切都是用于用户视图的用户数据)。该解决方案使XSS攻击无法进行。这意味着服务器端cookie块javascript可以读取或写入此cookie。并且每个重新加载页面都需要您使用带有refresh_token cookie的“ autoLogin”请求进行重新授权(每个请求都使用自动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(我是用户TypeScript)

/**
 * 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,
  }
]

如果您使用Laravel路由器,可能会采用类似的方式