Когда пользователь входит в систему, я отправляю обратно cookie HttpOnly в ответ.
Однако, когда я пытаюсь прочитать куки, когда ясделать последующий вызов API, там ничего нет
Вот как я сделал cookie:
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
Middleware (здесь достигается 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
пусто, есть что-то, что яотсутствует