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

问题描述 投票:0回答:1

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

问题是,很难找到有关在cookie(特别是Laravel + Vue)中存储令牌的教程。谁能帮忙实现如何在Cookie中存储令牌?

非常感谢任何可以提供帮助的人。

这是我当前的代码。

Controller

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>
laravel vue.js single-page-application laravel-passport bearer-token
1个回答
0
投票

使用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;
© www.soinside.com 2019 - 2024. All rights reserved.