Closed rzb closed 2 years ago
I had the same problem. Fixed it using this in plugins/axios.ts
export default function ({ $axios, redirect, error }: any, _inject: any) {
$axios.onError((error:any) => {
const status = parseInt((<any>error).response.status.toString());
if (status === 401) {
if (app.$auth.loggedIn) {
app.$auth.logout().then();
redirect('/login');
}
}
else if (status === 419) {
$axios.$get('/sanctum/csrf-cookie').then();
}
});
}
In my case the user logs out automatically if the nuxt-auth cookie is expired, but when he try to login and the if laravel cookie has not expired, then it will give you an error. So I have written a simple function to logout and then try again.
async login() {
let loginCount = 0;
do {
this.$nuxt.$loading.start();
try {
await this.$auth.loginWith('laravelSanctum', {
data: { email, password }
});
this.$router.push('/', () => this.$nuxt.$loading.finish);
break;
} catch (err) {
// If nuxt-auth expired but laravel cookie doesn't
if (err.message === 'Network Error' && !loginCount) {
await this.$auth.logout();
loginCount = 1;
} else {
this.$alert.show(err, 'error');
this.$nuxt.$loading.finish();
break;
}
}
} while (loginCount === 1);
}
Version
module: 5.0.0-1622918202.e815752 nuxt: 2.13.0
Nuxt configuration
[mode]
Nuxt configuration
Steps to reproduce
What is expected?
Ideally, the User should be logged out and redirected to login page right after cookie expiration, without waiting for him to click around. But redirecting on 401 is at least better than error page.
What is actually happening?
Nuxt 401 error page.
Additional comments
It's mentioned in issue #424 that Auth v5 has this fixed, so either the fix only works for token based auth or my config is messed up.