英文:
@nuxt/auth send me to /login page when I reload the page or access URLs manually
问题
我正在尝试在我的应用程序(Nuxt 2)中使用 @nuxt/auth 实现登录系统。后端是一个使用会话和Cookie的Node.js + Express + Passport。
我认为需要指出的是,我在前端使用了http-proxy-middleware,因此我的后端可以在与localhost:3000/api/...或localhost:3000/uploads上的相同域中访问。
后端似乎按预期工作,创建会话,如果已登录则返回User对象,如果未登录则返回401。我进行了一些研究,没有发现使用JWT的太多优势,所以我选择了会话和Cookie(但任何建议都是有效的)。 Cookie的过期时间在后端设置为24小时。
在前端,我没有使用自定义中间件。
在前端,我可以登录并被重定向到主页('/'),并且可以访问受保护的页面。我已全局设置了身份验证,但在登录布局中排除了auth: false。
但是,当我刷新页面或尝试手动访问某个URL(例如/timeline)时,它会回到登录页面。我尝试在登录页面上显示$auth.user,它显示了我登录时的用户信息。$auth.loggedIn为true。
需要注意的一点是,在第一秒$auth.loggedIn显示为false,可能与此有关?我检查了Cookie,似乎一切都没问题,我将在下面提供更多信息(这是在登录页面上)。
当我尝试访问我的后端端点/api/user时,我可以获取用户的信息,所以我确信在我的后端中已登录。
另外,当我尝试注销时,一开始它注销了我,但没有重定向我到登录页面。当我尝试访问受保护的页面时,它确实像预期的那样将我重定向。
但是,我希望在刷新或手动访问URL时不被重定向到登录页面,如何修复这个问题?
这是我的nuxt.config.js:(将代码部分留空)
我的登出代码非常简单:
(将代码部分留空)
这些是Cookie的情况:
当我注销并尝试第一次登录时(也许这个Cookie是来自以前的会话):
当我已登录并被重定向到主页时:
当我使用链接访问其他受保护的页面时:
当我尝试手动访问URL并被重定向到/login时:
如果需要的话,我可以分享一些我的后端代码,但我认为问题出在我的前端...
编辑
我刚刚意识到,我在登录后使用了this.$router.push('/'),并没有对重定向进行任何配置,所以我更新了我的nuxt.config.js,现在它在没有使用$router.push的情况下重定向,还在注销时重定向。但是刷新/手动访问的问题仍然存在。
(将代码部分留空)
英文:
I'm trying to implement a login system in my app (Nuxt 2) using @nuxt/auth. The backend is a Node.js + Express + Passport, using sessions and cookies.
I think it's important to say I'm using http-proxy-middleware in my front end, so my back end can be accessible in the same domain with localhost:3000/api/... or localhost:3000/uploads for uploaded files.
The backend seems to be working as expected, creating the sessions, returning an User object if logged in and 401 if not. I did some research and didn't find much advantages to use JWT so I opted for sessions and cookies instead (but any recommendations are valid). Cookies expiration time is set in the backend as 24 hours.
In my front end I don't have any custom middlewares.
In the front end, I can log in and it redirects me to home ('/'), and I can access protected pages, I have set auth globally but excluded from the login layout with auth: false.
But when I refresh the page or try to access some URL manually (e.g. /timeline) it goes back to the login page. I tried to show $auth.user in the login page and it's showing me the user's information as it was logged in. $auth.loggedIn is true.
One important thing to note is that it takes a while to show the information in $auth.user and $auth.loggedIn shows as false at the first second, maybe something to do with this? I checked the cookies and it seems to be all right, I will post more information below. (this in the login page)
When I tried to access my back end endpoint /api/user I get the user's information so I'm sure in my backend I'm logged in.
Also when I try to log out, at the first moment it logs me out but doesn't redirect to me to the login page. When I try to access some protected page it does redirect me as expected.
But I was expecting to not being redirected to login page when refreshing or accessing URLs manually, how can I fix this please?
This is my nuxt.config.js:
const { createProxyMiddleware } = require('http-proxy-middleware')
export default {
head: {
// ...
},
serverMiddleware: [
createProxyMiddleware('/api', {
target: 'http://localhost:3300/api',
changeOrigin: true,
pathRewrite: {
'^/api': '/'
}
}),
createProxyMiddleware('/uploads', {
target: 'http://localhost:3300',
changeOrigin: true,
pathRewrite: {
'^/uploads': '/uploads'
}
}),
],
router: {
middleware: ['auth']
},
// css: [],
css: [
'~assets/scss/main.scss',
],
// loading bar
loading: {
color: '#ef443b',
},
plugins: [
'~/plugins/vuelidate'
],
components: true,
buildModules: [
'@nuxtjs/eslint-module',
'@nuxtjs/style-resources',
'@nuxtjs/fontawesome',
],
modules: [
'bootstrap-vue/nuxt',
'@nuxtjs/axios',
'@nuxtjs/auth',
'nuxt-precompress',
],
auth: {
cookie: {
options: {
maxAge: 24 * 60 * 60 * 1000, // 24 hrs
secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production', // HTTP if local, HTTPS if production
},
},
strategies: {
local: {
token: {
required: false,
type: false
},
endpoints: {
login: {
url: '/api/login',
method: 'POST',
propertyName: false
},
logout: {
url: '/api/logout',
method: 'GET'
},
user: {
url: '/api/user',
method: 'GET',
propertyName: false
},
},
tokenRequired: false,
// tokenType: 'Bearer',
},
},
},
bootstrapVue: {
bootstrapCSS: false, // Or `css: false`
bootstrapVueCSS: false // Or `bvCSS: false`
},
fontawesome: {
component: 'fa',
suffix: false,
icons: {
regular: true,
solid: true,
brands: true,
},
},
styleResources: {
scss: [
'./assets/scss/_variables.scss',
'./assets/scss/_mixins.scss',
],
hoistUseStatements: true,
},
axios: {
baseURL: '/',
withCredentials: true,
credentials: true,
},
env: {
apiUrl: process.env.API_URL,
},
publicRuntimeConfig: {
axios: {
browserBaseURL: process.env.BROWSER_BASE_URL
}
},
privateRuntimeConfig: {
axios: {
baseURL: process.env.BASE_URL
}
},
build: {
transpile: [
'audiomotion-analyzer'
]
},
}
My logout code is as simple as this:
methods: {
logout(e) {
this.$auth.logout()
},
},
These are the cookies when:
I log out and try to log in for the first time (maybe this cookie is from past sessions):
When I'm logged in and redirected to home:
When I access another protected page using a link:
When I try to access an URL manually and gets redirected to /login:
If necessary I can share some code from my backend too, but I think the problem is in my front-end...
EDIT
I just realized I was using this.$router.push('/') after logging in and had no config whatsoever for redirections, so I updated my nuxt.config.js and now it is redirecting without $router.push, and also when I log out. The refresh / manually access problem persists tho.
auth: {
cookie: {
options: {
maxAge: 24 * 60 * 60 * 1000, // 24 hrs
secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production', // HTTP if local, HTTPS if production
},
},
strategies: {
local: {
token: {
required: false,
type: false
},
endpoints: {
login: {
url: '/api/login',
method: 'POST',
propertyName: false
},
logout: {
url: '/api/logout',
method: 'GET'
},
user: {
url: '/api/user',
method: 'GET',
propertyName: 'user'
},
},
tokenRequired: false,
// tokenType: 'Bearer',
},
},
redirect: {
login: '/login',
logout: '/login',
home: '/',
},
},
答案1
得分: 1
Answering my own question, for anyone who can stumble on the same or similar problem...
I even tried to create and implement a new auth module from scratch for 3 days because of this, just to get stuck on the same problem, turns out my axios wasn't set with the correct baseURL, I'm not sure where I've got this part of the code from, but I hadn't my .env vars set correctly, so when in SSR axios was requesting the wrong URL, but it was working on the client side somehow. This part of the code here in my nuxt.config.js:
axios: {
baseURL: '/',
withCredentials: true,
credentials: true,
},
// ...
publicRuntimeConfig: {
axios: {
browserBaseURL: process.env.BROWSER_BASE_URL
}
},
privateRuntimeConfig: {
axios: {
baseURL: process.env.BASE_URL
}
},
I just added to .env:
BASE_URL = 'http://localhost:3000/'
BROWSER_BASE_URL = 'http://localhost:3000/'
So if anyone is experiencing a similar problem try to check out your axios configuration!
I'm not sure why but even when I deleted 'publicRuntimeConfig' and 'privateRuntimeConfig' axios baseURL was still wrong... Also pay attention to the option being baseURL, not baseUrl as I saw other people with similar problems because of wrong case.
Hope this helps other people.
英文:
Answering my own question, for anyone who can stumble on the same or similar problem...
I even tried to create and implement a new auth module from scratch for 3 days because of this, just to get stuck on the same problem, turns out my axios wasn't set with the correct baseURL, I'm not sure where I've got this part of the code from, but I hadn't my .env vars set correctly, so when in SSR axios was requesting the wrong URL, but it was working on the client side somehow. This part of the code here in my nuxt.config.js:
axios: {
baseURL: '/',
withCredentials: true,
credentials: true,
},
// ...
publicRuntimeConfig: {
axios: {
browserBaseURL: process.env.BROWSER_BASE_URL
}
},
privateRuntimeConfig: {
axios: {
baseURL: process.env.BASE_URL
}
},
I just added to .env:
BASE_URL = 'http://localhost:3000/'
BROWSER_BASE_URL = 'http://localhost:3000/'
So if anyone is experiencing a similar problem try to check out your axios configuration!
I'm not sure why but even when I deleted 'publicRuntimeConfig' and 'privateRuntimeConfig' axios baseURL was still wrong... Also pay attention to the option being baseURL, not baseUrl as I saw other people with similar problems because of wrong case.
Hope this helps other people.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论