我知道使用HttpOnly cookie来存储用户令牌比将其存储在localstorage中更为可取,因为它可以防止任何狡猾的javascript客户端将其传递给客户端。
api服务器会成功创建cookie并将其发送到客户端,但是当您发出请求时,cookie不会发送,因此不会发生授权。
这是创建cookie的用户登录路径
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const { User, validate } = require('@models/user')
const express = require('express')
const router = express.Router()
const fs = require('fs')
const path = require('path')
router.post('/', async (req, res) => {
// First Validate The HTTP Request
const { error } = validate(req.body)
if (error) {
return res.status(400).send(error.details[0].message)
}
// Now find the user by their email address
let user = await User.findOne({ email: req.body.email })
if (!user) {
return res.status(400).send('Incorrect email or password.')
}
// Then validate the Credentials in MongoDB match
// those provided in the request
const validPassword = await bcrypt.compare(req.body.password, user.password)
if (!validPassword) {
return res.status(400).send('Incorrect email or password.')
}
var signOptions = {
expiresIn: '30d',
algorithm: 'RS256'
}
var CurrentDate = new Date()
CurrentDate.setMonth(CurrentDate.getMonth() + 1)
var cookieOptions = {
httpOnly: true,
expiresIn: CurrentDate,
secure: true
}
const token = jwt.sign({ _id: user._id },
fs.readFileSync(path.resolve('src/routes/keys/private.key'), 'utf8'),
signOptions)
res.status(200).cookie('stickyAccessJwt', token, cookieOptions).send(`Successfully logged in as ${user.email} done`)
})
module.exports = router
这是标题
这里是总是打“无效或缺失”的授权中间件
const jwt = require('jsonwebtoken')
const fs = require('fs')
const path = require('path')
const { User } = require('@models/user')
let authorisation = (req, res, next) => {
console.log(req.cookies)
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/public.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()
}
})
}
}
}
exports.authorisation = authorisation
对不起,如果我错过了值得分享的内容。
是否与本地运行的所有内容有关?如果是这样,在部署时,应采取什么步骤来确保其仍然有效?
我还可以使用其他安全方式来处理我可以在api上授权的用户登录吗?