reactjs - 已解決:使用 Express.Request 解密或取消簽名 Cookie?
我正在使用 Express.Response 創建 cookies,但在解密/取消簽名它們時遇到困難。以下是我創建 cookies 的方式(這一切都在伺服器端發生,所以沒有瀏覽器相關的操作):
在 server/index.ts 中:
import express from 'express'
import Router from 'express-promise-router'
import cookieParser from 'cookie-parser'
import UserRoutes from './routes/UserRoutes'
const app = express() // creating the app
app.use(cookieParser('secret')) // setting the cookie secret
app.use(cors({
origin: true,
credentials: true
})
const router = Router() // creating the router
router.use(UserRoutes) // router using UserRoutes
app.use(router) // app using the router
在 UserRoutes 中:
import Router from 'express-promise-router'
import * as UserController from '../controllers/UserController'
const router = Router()
router.route('/user/login').post(
UserController.loginUser
)
在 UserController 中:
import Express from 'express'
import cookieParser from 'cookie-parser'
import signature from 'cookie-signature'
import { v4 as uuid } from 'uuid'
export const loginUser = async (req: Express.Request, res: Express.Response) => {
// stuff here dealing with username and password - not important
const newToken = uuid() // creating a long random token
console.log(newToken) // a2af2c05-2135-4e9c-9fc0-cc10fb8e5dfb ==> correct cookie value
// creating 'User' cookie with newToken as value
res.cookie('User', newToken, { httpOnly: true, signed: true })
console.log(req.signedCookies.User) // e57583d0-09a4-4a49-98d5-50e966782b8f ==> different because it is 'signed'
// trying decrypting and unsigning the cookie
// this returns the same value as the cookie is not encrypted
console.log(cookieParser.signedCookie(req.signedCookie.User, 'secret')) // e57583d0-09a4-4a49-98d5-50e966782b8f
// this returns 'false', I guess because it is the wrong secret
console.log(signature.unsign(req.signedCookies.User, 'secret')) // false
}
有沒有想過為什麼 'User' cookie 無法被解密或取消簽名?我在 app.use(cookieParser('secret')) 中使用了相同的密鑰,並在嘗試解密或取消簽名時遇到問題。
謝謝你的幫助
解決方案:結果發現,在創建 req.signedCookies.User 的相同範圍/函數中檢索它會導致問題。我創建了一個 authenticate 函數,該函數會在任何其他路由函數之前被調用,一切似乎運作良好。