boyjarv's avatar

Logout says 401 unauthorized

I am currently at time 1:20:12 on this video: https://www.youtube.com/watch?v=WLQDpY7lOLg&t=4665s

I have followed along very carefully and even looked at the author's github repo.

I am trying to implement the logout method and action etc but I am getting 401 unauthorized

AuthController:

public function logout()
    {
        /** @var User $user */
        $user = Auth::user();
        // Revoke the token that was used to authenticate the current request...
        $user->currentAccessToken()->delete();

        return response([
            'success' => true
        ]);
    }

DefaultLayout:

function logout() {
  store.dispatch("logout").then(() => {
    router.push({
      name: "Login",
    });
  });
}

Store:

logout({commit}) {
      return axiosClient.post('/logout')
      .then(response => {
        commit('logout')
        return response;
      })
    },

Api:

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });
    Route::post('/logout', [AuthController::class, 'logout']);
});
0 likes
1 reply
boyjarv's avatar

I sorted it, the author changed his axios.js file:

import axios from "axios";
import store from "./store";
import router from "./router";

const axiosClient = axios.create({
  baseURL: `http://localhost:8000/api`
})

axiosClient.interceptors.request.use(config => {
  config.headers.Authorization = `Bearer ${store.state.user.token}`
  return config;
})

axiosClient.interceptors.response.use(response => {
  return response;
}, error => {
  if (error.response.status === 401) {
    sessionStorage.removeItem('TOKEN')
    router.push({name: 'Login'})
  } else if (error.response.status === 404) {
    router.push({name: 'NotFound'})
  }
  return error;
})

export default axiosClient;

Please or to participate in this conversation.