Search code examples
laravelvue.jssingle-page-applicationlaravel-passportbearer-token

Laravel / Vue Passport (SPA) - Store token to cookies


I have been following a tutorial about Vue + Laravel authentication and everything is set-up but then the tutorial went to storing tokens in a local storage. I have read that this is not the best practice that should be followed since it is more susceptible to an XSS attack.

The problem is that it is very hard to find a tutorial about storing tokens in a cookie (specifically Laravel + Vue). Can anyone please help on how to implement storing tokens in a cookie?

Thank you very much for anyone who could help.

Here is my current code.

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 routes

Route::post('/login', 'AuthController@login');
Route::middleware('auth:api')->post('/logout', 'AuthController@logout');

Vue Component Script

<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>

Solution

  • Use document.cookie = response.data.token to store token in 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

    to get cookie

    var token = document.cookie;