首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Nuxt中cookie过期时自动注销用户?

如何在Nuxt中cookie过期时自动注销用户?
EN

Stack Overflow用户
提问于 2019-11-11 11:58:46
回答 3查看 2.8K关注 0票数 1

我正在使用official NuxtJS Auth Routes example通过express-sessions执行登录,它工作得很好

app.js文件

代码语言:javascript
复制
const express = require('express')
const session = require('express-session')
const app = express()

app.use(express.json())
app.use(express.urlencoded({ extended: true }))
// session middleware
app.use(
  session({
    secret: 'super-secret-key',
    resave: false,
    saveUninitialized: false,
    cookie: { maxAge: 60000 }
  })
)

// Create express router
const router = express.Router()

// Transform req & res to have the same API as express
// So we can use res.status() & res.json()
router.use((req, res, next) => {
  Object.setPrototypeOf(req, app.request)
  Object.setPrototypeOf(res, app.response)
  req.res = res
  res.req = req
  next()
})

// Add POST - /api/login
router.post('/login', (req, res) => {
  if (req.body.username === 'demo' && req.body.password === 'demo') {
    req.session.authUser = { username: 'demo' }
    return res.json({ username: 'demo' })
  }
  res.status(401).json({ message: 'Bad credentials' })
})

// Add POST - /api/logout
router.post('/logout', (req, res) => {
  delete req.session.authUser
  res.json({ ok: true })
})

app.use('/api', router)

module.exports = app

问题是,当cookie过期时,用户仍然在前端登录。如果他们访问一个端点,他们就会注销,因为我猜调用nuxtServerInit会取消用户的设置

store/index.js

代码语言:javascript
复制
import axios from 'axios'

export const state = () => ({
  authUser: null
})

export const mutations = {
  SET_USER(state, user) {
    state.authUser = user
  }
}

export const actions = {
  // nuxtServerInit is called by Nuxt.js before server-rendering every page
  nuxtServerInit({ commit }, { req }) {
    if (req.session && req.session.authUser) {
      commit('SET_USER', req.session.authUser)
    }
  },
  async login({ commit }, { username, password }) {
    try {
      const { data } = await axios.post('/api/login', { username, password })
      commit('SET_USER', data)
    } catch (error) {
      if (error.response && error.response.status === 401) {
        throw new Error('Bad credentials')
      }
      throw error
    }
  },

  async logout({ commit }) {
    await axios.post('/api/logout')
    commit('SET_USER', null)
  }
}
EN

回答 3

Stack Overflow用户

发布于 2019-11-11 13:19:18

如果没有websocket等待注销通知,您将无法在到期时立即注销用户。这就是为什么它会一直等待,直到您再次尝试导航。如果想要立即注销用户,可以创建一个Websocket,该套接字在cookie过期时等待来自服务器的信号。

https://github.com/nuxt/nuxt.js/tree/dev/examples/with-sockets

但是,这是一个特定的用例。大多数网站只是等待用户尝试另一个需要检查令牌过期的操作,然后采取适当的措施。

可以通过跟踪商店中前端的过期时间来完成此操作的简化版本。然后,您可以使用computed属性来检查用户剩余时间的不断递减倒计时。当它达到零时,你就可以运行你的突变了。

票数 1
EN

Stack Overflow用户

发布于 2019-11-20 14:24:03

您可以注册一个服务工作者来异步侦听cookie存储中的更改(这也不需要连续轮询!)这是相当新的,对某些浏览器的支持可能还不存在。Here就是一篇关于它的文章。

或者,您可以使用Push API通知前端过期并调用logOut方法。您的服务器应该能够跟踪过期并发送推送。

如果他们访问一个端点,他们会被注销,因为我猜调用nuxtServerInit会取消用户的设置。

老实说,这几乎是大多数网站的默认行为。除非您在构建are应用程序时首先考虑安全性。

票数 1
EN

Stack Overflow用户

发布于 2019-11-12 11:02:06

非常接近这里的答案。这个想法是在用户发布到登录路由时设置req.session.expires。目前的问题出在异步登录方法内部,如何访问req.session?

这是server/index.js文件

代码语言:javascript
复制
// Add POST - /api/login
router.post('/login', (req, res) => {
  if (req.body.username === 'demo' && req.body.password === 'demo') {
    req.session.authUser = { username: 'demo' }
    req.session.expires = req.session.cookie.expires.getTime()
    return res.json({ username: 'demo' })
  }
  res.status(401).json({ message: 'Bad credentials' })
})

这是store/index.js文件

代码语言:javascript
复制
export const actions = {
  // nuxtServerInit is called by Nuxt.js before server-rendering every page
  nuxtServerInit({ commit }, { req }) {
    if (req.session && req.session.authUser) {
      commit('SET_USER', req.session.authUser)
    }
    if (req.session && req.session.expires) {
      commit('SET_EXPIRES', req.session.expires)
    }
  },
  // How do you get req.session.expires HERE???
  async login({ commit }, { username, password }) {
    try {
      const response = await this.$axios.post('/api/login', {
        username,
        password
      })
      console.log(response, response.request, response.request.session)
      commit('SET_USER', response.data)
    } catch (error) {
      if (error.response && error.response.status === 401) {
        throw new Error('Bad credentials')
      }
      throw error
    }
  },

  async logout({ commit }) {
    await this.$axios.post('/api/logout')
    commit('SET_USER', null)
    commit('SET_EXPIRES', null)
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58795369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档