oliverbusk
324
2
Vue

Vue / Laravel - Handle logout correctly

Posted 7 months ago by oliverbusk

Hi there I am currently trying to create a simple SPA using Vue and Laravel. I've got the basics to work - users can register and login.

I just can't figure out how to create a logout function.

This is what I currently have:

AuthController.php:

public function logout()
    {
        $accessToken = auth()->user()->token();

        $refreshToken = DB::table('oauth_refresh_tokens')
        ->where('access_token_id', $accessToken->id)
        ->update([
            'revoked' => true
        ]);

        $accessToken->revoke();

        return response()->json(['status' => 200]);
    }

routes/api.php:

Route::middleware('auth:api')->group(function () {
    Route::post('/logout', 'API\[email protected]');
    Route::get('/get-user', 'API\[email protected]');
});

Right now, this is what I have tried to do:

Layout.vue:

methods: {
            logout() {
                axios.post('/api/logout').then(response => {
                    this.$router.push("/login")

                }).catch(error => {
                    location.reload();
                });
            }
 }

Which calls my logout function in Auth.js:

logout() {
        localStorage.removeItem('token')
        localStorage.removeItem('expiration')
}

However, when users click on the logout function, they are not logged out immediately (redirected to the login page) - they can still browse "user only pages".

I have to refresh the page before I am properly logged out.

Can anyone assist me with this? Is this even the right approach to a "secure" logout function?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.