Perform the normal settings suggested by the official documentation
loggedIn must not be true when the user is not logged in.
I just launch the server, loggedIn gets set to true even if I did not authenticate the user and , even when I clear the browser's cache, history, data ... even when my REST API server is off.
I saw similar issues related to this. I applied every single solution I found in vain.
I am not using sessions, cookies or whatever. I just want to store my JWT token in localStorage. Whether this JWT is stored or not, loggedIn is always true.
This bug made me loosing trust in this module because almost all other functionalities depend on this famous loggedIn flag
Facing same issue
Same here. Is there a workaround?
Have you tried downgrading nuxt to 2.4.5? This helped with my issue. Google login through nuxt-auth stopped working properly ( if (!app.$auth || !app.$auth.loggedIn) { ) was actually returning true (so loggedIn was false after successful login).
Have you tried downgrading nuxt to 2.4.5? This helped with my issue. Google login through nuxt-auth stopped working properly ( if (!app.$auth || !app.$auth.loggedIn) { ) was actually returning true (so loggedIn was false after successful login).
Downgrading? I use "nuxt": "^2.4.0".
Any ideas how can I fix the main problem?
Sorry, no idea about the root cause of this issue. I just wanted to signal, that there's something wrong with google login with nuxt @2.5.x and simply downgrading to 2.4.5 fixed my issue.
npm i [email protected]
I did not try to downgrade because in my particular case that is not a good option. But thank you for the feedback.
Also, $auth.loggedIn will not be synced with Vuex!
If I use $auth.loggedIn after user sign-in and router push, It still gives me the state of false, while it is expected to be true.
There's no problem when using $store.state.auth.loggedIn
Unfortunately, I don't have enough time till the weekend, so could anyone report this bug??
@mehrunrasoli $store.state.auth.loggedIn is always true, and that is a problem.
Think I found the issue:
https://github.com/nuxt-community/auth-module/blob/8c1567a9fd77bcebb5af41a1be31740dfded95a8/lib/schemes/local.js#L75
When the user endpoint is disabled, it'll always set the user to {}, thus setting loggedIn to true.
You can see the two if statements reversed here:
https://github.com/nuxt-community/auth-module/blob/8c1567a9fd77bcebb5af41a1be31740dfded95a8/lib/schemes/oauth2.js#L90
Interesting. I will check that. Thank you @ineedbots
(I found a workaround to make it work, but I will share it when I will do a full investigation about it)
Indeed, it seems the default behavior is to set up the user endpoint
I stumbled on that as well. I ditched the out-of-the-box local scheme and went with a custom scheme that's essentially a (slightly) edited version of 'local'. I could never get the local scheme working.
I'm using an API created by Strapi, so, for example, there's no logout endpoint. And the user endpoint is /users/me. I also added a bunch of event emitters to figure out what the heck the scheme was actually doing -- and when it was doing it. I listen for the events on a debugger component that just logs everything out to the console.
I created a schemes folder and then a file called strapi.js:
import { EventBus } from '~/event-bus'
export default class LocalScheme {
constructor(auth, options) {
this.$auth = auth
this.name = options._name
this.options = Object.assign({}, DEFAULTS, options)
}
_setToken(token) {
if (this.options.globalToken) {
// Set Authorization token for all axios requests
this.$auth.ctx.app.$axios.setHeader(this.options.tokenName, token)
EventBus.$emit('debug', ` _setToken(): ${token}`)
}
}
_clearToken() {
if (this.options.globalToken) {
// Clear Authorization token for all axios requests
this.$auth.ctx.app.$axios.setHeader(this.options.tokenName, false)
EventBus.$emit('debug', ` _clearToken(): ${this.options.tokenName}`)
}
}
mounted() {
if (this.options.tokenRequired) {
const token = this.$auth.syncToken(this.name)
this._setToken(token)
EventBus.$emit('debug', ` mounted() => this._setToken(${token})`)
}
EventBus.$emit('debug', ` mounted() => this.$auth.fetchUserOnce()`)
return this.$auth.fetchUserOnce()
}
async login(endpoint) {
if (!this.options.endpoints.login) {
return
}
// Ditch any leftover local tokens before attempting to log in
await this._logoutLocally()
try {
const result = await this.$auth.request(
endpoint,
this.options.endpoints.login
)
EventBus.$emit('debug', `login(): ${result}`)
if (this.options.tokenRequired) {
const token = this.options.tokenType
? this.options.tokenType + ' ' + result
: result
this.$auth.setToken(this.name, token)
this._setToken(token)
}
return this.fetchUser()
} catch (e) {
EventBus.$emit('error', e.response.data)
EventBus.$emit('debug', `Error: ${JSON.stringify(e.response.data)}`)
console.log(e)
}
}
async setUserToken(tokenValue) {
// Ditch any leftover local tokens before attempting to log in
await this._logoutLocally()
if (this.options.tokenRequired) {
const token = this.options.tokenType
? this.options.tokenType + ' ' + tokenValue
: tokenValue
this.$auth.setToken(this.name, token)
this._setToken(token)
}
EventBus.$emit('debug', `setUserToken(): ${token}`)
return this.fetchUser()
}
async fetchUser(endpoint) {
// User endpoint is disabled.
// if (!this.options.endpoints.user) {
// this.$auth.setUser({})
// return
// }
// Token is required but not available
if (this.options.tokenRequired && !this.$auth.getToken(this.name)) {
return
}
// Try to fetch user and then set
try {
const user = await this.$auth.requestWith(
this.name,
endpoint,
this.options.endpoints.user
)
this.$auth.setUser(user)
EventBus.$emit('debug', `fetchUser(): ${JSON.stringify(user)}`)
} catch (e) {
EventBus.$emit('debug', `fetchUser() error: ${e}`)
}
}
async logout(endpoint) {
// Only connect to logout endpoint if it's configured
if (this.options.endpoints.logout) {
await this.$auth
.requestWith(this.name, endpoint, this.options.endpoints.logout)
.catch(() => {})
}
// But logout locally regardless
return this._logoutLocally()
}
async _logoutLocally() {
if (this.options.tokenRequired) {
this._clearToken()
}
EventBus.$emit('debug', '_logoutLocally() => this.$auth.reset()')
return this.$auth.reset()
}
}
const DEFAULTS = {
tokenRequired: true,
tokenType: 'Bearer',
globalToken: true,
tokenName: 'Authorization'
}
Then in my nuxt.config.js I use the strapi scheme:
auth: {
plugins: ['~/plugins/auth.js'],
cookie: true,
resetOnError: true,
redirect: {
login: '/login',
logout: '/',
callback: '/login',
home: '/'
},
strategies: {
// local: false,
strapi: {
_scheme: '~/schemes/strapi.js',
endpoints: {
login: {
url: '/auth/local',
method: 'post',
propertyName: 'jwt'
},
user: {
url: '/users/me',
method: 'get'
}
}
}
}
},
And in login.vue, my authenticate method looks like this:
methods: {
authenticate() {
this.$auth.loginWith('strapi', {
data: {
identifier: this.$refs['identifier'].value,
password: this.$refs['password'].value
}
})
},
I also had issues with redirecting after authenticating. I ended up using the auth plugin here referenced here: https://github.com/nuxt-community/auth-module/issues/134
Anyway, I think -- think -- I have it working now. I'm using it in a new project w/Nuxt 2.6.3, and it works as I expect -- no issues.
@cschweda So you set the user endpoint as @ineedbots suggested.
Thank you both.
In fact setting the user endpoint as suggested above by @ineedbots does not work either. After I implemented it, I remembered finally I tried this option before complaining here (and after using a trick of my own which is not too clean to share). I also found some bloggers who set this user endpoint but logging out does not protect the authenticated routes.
Just in case this be helpful for someone: I do not face this issue with some other Nuxt.js versions I tested.
I do confirm that we experience the same issue. When setting user to false an empty object is set, which sets loggedIn to true.
This function is responsible for that. The Boolean on an empty object ({}) returns true.
Which Nuxt.s version are you using ? @BabyDino
@begueradj v2.10.1
thanks to @cschweda, I got an idea. I had similar problem and solved it by cloning the localscheme into a custom one.
the only difference I made was at the end of the fetchUser function. replacing requestWith with simply request.
// Try to fetch user and then set
const user = await this.$auth.request(
this.options.endpoints.user.url,
'/user/data/'
)
this.$auth.setUser(user)
Now, it's working as expected.
This seems to still be happening to me with the following versions:
"@nuxtjs/auth": "^4.9.1",
"@nuxtjs/axios": "^5.12.0",
"nuxt": "^2.13.0"
I'm using regular sessions and not jwt. Or at least trying to, I might have messed up something with my configuraiton. Here's the relevant part of the nuxt.config.js:
auth: {
strategies: {
local: {
endpoints: {
login: {
url: '/api/auth/register_login',
method: 'post'
},
logout: {
url: '/api/auth/logout',
method: 'get'
},
user: {
url: '/api/auth/user',
method: 'get',
propertyName: false
}
},
tokenRequired: false,
tokenType: false
}
}
}
Here's a link to a stripped version of my project with only the authentication bit present:
https://github.com/bilthon/nuxt-auth-demo
Hi @bilthon! This issue was fixed in dev version, but it will only be released in v5. For now you can use the package of dev version @nuxtjs/auth-next. Then try to use cookie scheme.
Please, check the updated docs because we changed a lot of things: https://dev.auth.nuxtjs.org/
(Sorry for accidentally closing the issue)
Ok, I finally got to test the cookie scheme described in v5, but it seems like cookies are stored in the vuex store. Why is that so? I thought cookies had their own place in a browser segregated from the local store.
Closing as fixed in v5. If you're still seeing the cookie/vuex problem, please file a separate issue.
Most helpful comment
Facing same issue