How to keep users logged in after browser close with nuxt auth? - vue.js

I have the following inside my nuxt.config.js file:
auth: {
strategies: {
local: {
scheme: 'local',
token: {
property: 'meta.token',
global: true,
},
user: {
property: 'data',
},
endpoints: {
login: { url: '/auth/login', method: 'post' },
logout: { url: '/auth/logout', method: 'post' },
user: { url: '/auth/user', method: 'get' }
}
},
}
},
After a short (but still unknown amount of time for me), user is logged out. Also, after closing and opening the browser, user is always logged out. How could I persist the logged in state even after closing the browser? Also, why could be the reason for users be logged out after a short amount of time?
Inspecting cookies I have in my bearer token:
Expires / Max-Age:"Session"
And I have in my local storage:
auth._token_expiration.local:"1656703495434"

Using this.$auth.$storage.setUniversal('user', response.data, true) was enough to solve OP's issue.
As shown here: https://auth.nuxtjs.org/api/storage/#universal-storage

Related

Using nuxt.js auth with multiple app in the same PC

I have two apps using auth module and nuxt.js running in my PC .
I am used auth local strategies at both app.
I have a problem when I am logged(authenticated) in my first app, the second app doesn´t ask for authentication(both apps in same PC).
I have to delete the localstorage with auth data, in order to my second app ask for login to authenticate.
My nuxt auth settings is in the nuxt.config.js is:
auth: {
localStorage: {
prefix: 'auth.',
},
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'data.access_token',
maxAge: 1800,
type: 'Bearer',
required: true,
},
refreshToken: {
property: 'data.refresh_token',
maxAge: 60 * 60 * 24 * 30,
},
user: {
property: 'data',
autoFetch: true,
},
endpoints: {
login: {
url: 'user/login',
method: 'post',
},
refresh: { url: 'user/refreshToken', method: 'post' },
user: { url: 'user/me', method: 'get' },
logout: false,
},
},
},
redirect: {
login: '/login',
logout: '/login',
// callback: '/dash',
// home: '/clientes',
home: '/',
},
},
Is there some special settings in the config to avoid it
I have tried to use a different localstore prefix, but no look
NuxtJs has localStorage enabled by default as a session persistence engine.
auth: {
localStorage: {
prefix: 'auth.'
}
}
You need to provide a different prefix in your localStorage configuration (of course, if you intend to continue using localStorage) for each of your projects. That should make sure both apps don't look for the session token in the same key.
This is what you're looking for
https://auth.nuxtjs.org/api/options/#localstorage
There's an option for cookies as well, but the logic remains the same.

Nuxt Auth Module c5 doesn't refresh token automatically when token expires

Version
module: 5.0.0-1624817847.21691f1
nuxt: 2.15.8
Nuxt configuration
Universal
Nuxt configuration
// Auth: https://auth.nuxtjs.org/ (v5)
auth: {
redirect: {
login: '/account/login/',
logout: '/account/login/',
callback: '/account/login/',
home: '/account/beams/'
},
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'access_token',
maxAge: 120, // seconds, 2 minutes
global: true
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
maxAge: 1209600 // seconds, 2 weeks
},
user: {
property: 'user',
autoFetch: true
},
endpoints: {
login: { url: '/api/account/login', method: 'post', propertyName: 'token' },
refresh: { url: '/api/account/refresh', method: 'post', },
logout: { url: '/api/account/logout', method: 'post' },
user: { url: '/api/account', method: 'get' }
},
autoLogout: false
}
}
},
Additional information
Checklist
[x] I have tested with the latest Nuxt version and the issue still occurs
[x] I have tested with the latest module version and the issue still occurs
[x] I have searched the issue tracker and this issue hasn't been reported yet
Steps to reproduce
What is expected?
When a user's token expires and refresh scheme is implemented, a user shouldn't be logged out and redirected back to the login screen, the refresh token should be used to obtain a new token and the transition should be seamless allowing any authenticated route to continue to work.
What is actually happening?
In my Nuxt project with the Auth module I've implemented the refresh scheme, however, when my token expires I don't see any request in my network being made to the refresh route after my token expires and I navigate to a protected page via the auth middleware.
I expect I'm missing some simple configuration?
My current token has an expiry of 1 minute for testing, and my refresh token has an expiry of 14 days for testing.
However, when adding:
scheme: 'refresh'
refresh: { url: '/api/account/refresh', method: 'post', }
the functionality appears to not be fetching my user and automatically logging me in.
My /api/account/refresh endpoint in my API returns the following:
{
refresh_token: 'my refresh token',
token_type: 'bearer',
expired_in: 5000
}
My /api/account/login endpoint in my API returns the following:
{
access_token: 'my token',
token_type: 'bearer',
expired_in: 1000
}
What am I missing?
You need to return refresh token from /api/account/login. And then set in conf property name of it.
I have same issue with very similar comfiguration. This is my result from API (I added refresh token to the result):
{
"access_token": "XXX",
"refresh_token": "XXX",
"expired_in": 3600,
"token_type": "bearer"
}
If I inspect cookies, I can see acces token, but refresh token does not set:
I try to manually set refresh token after login, but with same result:
const result = await this.$auth.loginWith('local', {
data: this.login,
})
this.$auth.setUserToken(result.data.accessToken, result.data.refreshToken)

How to set session using Nuxt-Auth?

I am trying to use Nuxt/auth, but run into problem with session saving in localStorage.
Login.vue
methods: {
sendLoginLink() {
this.$auth.loginWith('local', {
data: {
username: "test#gmail.com",
password: "testpassword"
}
}).then((date) => {
console.log("data", date)
}).catch((err) => {
console.error("err", err)
})
}
Nuxt.config.js
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/dashboard', method: 'post', propertyName: 'token' }
},
tokenType: ''
}
}
axios: {
baseURL: 'http://localhost:1234'
},
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth-next',
]
When the user logs in, the function sendLoginLink is called and throw error in console:
Which means that the auth-token is so large that it cannot be stored in localStorage, but all other things related to this function are saved in localStorage. For example:
I googled a lot but didn't find a good solution to the problem. For example, I tried to clear all localStorage memory before running sendLoginLink() function but the result is the same. Different browsers have the same problem

How to prevent nuxt auth to go to error page if the pass or email is wrong

I'm using NuxtJs v2.13 with its auth module and Laravel with passport for my backend. for login i use the documented method:
async signIn(formData){
await this.$auth.loginWith('local',{
data: formData
})
if(this.$auth.user.depth > 1){
this.goTo('/cms/product')
}else{
this.goTo('/')
}
}
when the email or password is wrong it send me too nuxt error page! i should remain on login page.
what should i do!!?
BTW, i gonna use vee-validate on my form too. and this is my auth config on nuxt.config.js:
auth: {
strategies: {
local: {
endpoints: {
login: { url: 'auth/login', method: 'post', propertyName: '' },
logout: { url: 'auth/logout', method: 'post' },
user: { url: 'auth/info', method: 'get', propertyName: 'data' }
}
}
},
redirect: {
login: '/login',
logout: '/',
callback: '/login',
home: '/'
},
cookie: {
prefix: 'auth.',
options: {
path: '/',
maxAge: process.env.AUTH_COOKIE_MAX_AGE
}
}
},
Nuxt is redirecting because the error isn't being handled. You can simply wrap this code in an error handler. It's also good to put this code near the login component or page so you can use the status code of the error to display some meaningful response to the user, e.g. that the credentials were invalid.
try {
await this.$auth.loginWith('local', {
data: formData,
})
if (this.$auth.user.depth > 1) {
this.goTo('/cms/product')
} else {
this.goTo('/')
}
} catch (error) {
if (error.response) {
// Get the error status, inform the user of the error.
}
// Unexpected error, tell the user to try again later.
}
Since the #nuxtjs/auth package requires the #nuxtjs/axios package you can also read about intercepting errors on a global level with Axios Interceptors. I personally use try/catch blocks at the method level and use interceptors for catching 401 Unauthenticated errors and deleting the user information from Vuex.

How can I login and access to my Django-Rest-Framework while running my Nuxt project local?

I use Django-Rest-Framework for my API. It is on a remote server in the internet.
Locally I have a Nuxt-JS application running which should consume the REST-API.
How can I access this API from my local machine?
1) I would like to get the CSRF token from my login page with axios. For example from: /accounts/login/
For this I would like to make a "GET" call and geht from the HTTP-HEADER my CSRF tocken. But how?
You can install #nuxt/auth module after which you can update your nuxt.config.js file as follows:
auth: {
redirect: {
login: 'your-login-redirect-path',
logout: 'your-logout-redirect-path',
home: 'your-home-path'
},
strategies: {
local: {
endpoints: {
login: { url: 'your-django-login-endpoint', method: 'post', propertyName: 'token' },
logout: { url: 'your-django-logout-endpoint', method: 'post' },
user: { url: 'your-django-userinfo-endpoint', method: 'get', propertyName: 'user' }
}
}
}
},
Check out Nuxt Auth for more info