gpt4 book ai didi

javascript - express - 如何在对 API 的请求中读取 HttpOnly cookie?

转载 作者:行者123 更新时间:2023-12-04 17:39:30 26 4
gpt4 key购买 nike

当用户登录时,我会在响应中发回一个 HttpOnly cookie。

enter image description here

但是,当我在随后调用 API 时尝试读取 cookie 时,什么也没有

这是我制作 cookies 的方法:

var signOptions = {
expiresIn: '30d',
algorithm: 'RS256'
}
var CurrentDate = new Date()
CurrentDate.setMonth(CurrentDate.getMonth() + 1)
var cookieOptions = {
httpOnly: true,
expires: CurrentDate
}

const token = jwt.sign({ _id: user._id },
fs.readFileSync(path.resolve('routes/keys/private.key'), 'utf8'),
signOptions)

res.status(200).cookie('stickyAccessJwt', token, cookieOptions).send('well done')

路线('/test'):
const express = require('express')
const router = express.Router()
const { CheckAuthorisation } = require('./middleware/checkAuthorisation')

router.get('/', CheckAuthorisation, async (req, res) => {
res.send(':)')
})

module.exports = router

中间件(此处到达 401):
let checkAuthorisation = (req, res, next) => {
var userJWT = req.cookies.stickyAccessJwt
if (!userJWT) {
res.status(401).send('Invalid or missing authorization token')
} else {
// 2. There's a token; see if it is a valid one and retrieve the payload

var verifyOptions = {
expiresIn: '30d',
algorithm: ['RS256']
}

const userJWTPayload = jwt.verify(
userJWT,
fs.readFileSync(path.resolve('routes/keys/private.key'), 'utf8'),
verifyOptions)

if (!userJWTPayload) {
// Kill the token since it is invalid
res.clearCookie('stickyAccessJwt')
res.status(401).send('Kill the token since it is invalid')
} else {
// 3. There's a valid token...see if it is one we have in the db as a logged-in user
User.findOne({ '_id': userJWTPayload._id })
.then(function (user) {
if (!user) {
res.status(401).send('User not currently logged in')
} else {
console.log('Valid user:', user.email)
next()
}
})
}
}
}

这是我的 index.js
const Joi = require('joi')
Joi.objectId = require('joi-objectid')(Joi)
const bodyParser = require('body-parser')
const cors = require('cors')
const cookieParser = require('cookie-parser')
const mongoose = require('mongoose')
const express = require('express')
const app = express()
const register = require('./routes/register')
const login = require('./routes/login')
const test = require('./routes/test')

mongoose.connect('mongodb://localhost/stickywall', { useNewUrlParser: true })
.then(() => console.log('Now connected to MongoDB!'))
.catch(err => console.error('Something went wrong', err))
mongoose.set('useCreateIndex', true)

app.use(cors())
app.use(cookieParser())
app.use(express.json())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use('/register', register)
app.use('/login', login)
app.use('/test', test)

const port = process.env.PORT || 4000
app.listen(port, () => console.log(`Listening on port ${port}...`))

我不明白为什么 req.cookies是空的,我有什么遗漏吗?

最佳答案

res.cookie([JWT_TOKEN=Bearer ${token}; secure; httponly; samesite=Strict; ,
])

  • 首先是安装cookie-parser库,它是一个中间件,所以express可以管理cookie:
  • $ npm install cookie-parser
  • 然后转到配置 Express 应用程序的位置并将 cookie-parser 库添加为中间件
  • $const express = require('express'); $const cookieParser = require('cookie-parser'); $app.use(cookieParser());3.现在我们的 Express 应用程序可以为我们完成所有的 cookie 解析工作!
    req.cookies.JWT_TOKEN
  • 前面如果使用axios一定要在配置中设置“withCredentials: true”
  • const config = { headers: { 'Content-Type': 'application/json', },withCredentials: true,}
    axios
    .post(
    'http://localhost:3008/api/auth/login',
    {
    username: target.username.value,
    password: target.password.value,
    },
    config
    )
    .then((data) => JSON.stringify(data, null, 2))
    .then((result) => console.log(result))
    .catch((err) => console.log('[Control Error ] ', err))
    }`
    !!! HTTP cookie 会在对服务器的所有请求中自动发送。结束

    关于javascript - express - 如何在对 API 的请求中读取 HttpOnly cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55129348/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com