当Cookie在Nuxt中过期时,如何自动注销用户?

我正在使用official NuxtJS Auth Routes example通过express-sessions登录,效果很好

app.js文件

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',res) => {
  delete req.session.authUser
  res.json({ ok: true })
})

app.use('/api',router)

module.exports = app

问题是cookie过期时,用户仍在前端登录。如果他们访问终结点计算机,则它们会注销,因为我猜测将调用nuxtServerInit来取消用户身份设置

store / index.js

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',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)
  }
}
pengmail 回答:当Cookie在Nuxt中过期时,如何自动注销用户?

让Websocket等待注销通知的时间很短,到期后将无法立即注销用户。这就是为什么它一直等到您再次尝试导航的原因。如果要立即注销用户,则可以创建一个Websocket,以在Cookie到期后等待来自服务器的信号。

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

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

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

,

您可以注册服务工作者以异步侦听cookie存储中的更改(这也无需连续轮询!)这是相当新的功能,可能不支持某些浏览器。 Here是其中的一篇文章。

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

  

如果他们访问端点,则由于我是   猜测会调用nuxtServerInit,这会使用户不满意。

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

,

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

这是server / index.js文件

// 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文件

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)
  }
}
本文链接:https://www.f2er.com/3126618.html

大家都在问