[英]HttpOnly cookies are not sent with request to server
我在 node express 中創建了 API 並在端口:8000
上運行它,我在端口:3000
上通過簡單的 CRA 使用 API。 我已經通過設置 httpOnly cookie 創建了注冊和登錄。 此外,我已經放置了中間件來檢查每個端點以驗證它是否具有該令牌。 當我通過 Thunder/Postman 進行測試時,一切正常,登錄后我得到 cookie 作為響應,我將該 cookie 設置為 auth 令牌並請求獲取數據,然后我得到了數據。
當我通過 React Frontend 登錄時,它成功了,我可以在 in.network 選項卡中看到我已經收到 cookie 作為響應。 但是當我向受保護的端點發出請求時,請求中沒有 cookie(我在服務器上記錄傳入請求並比較使用 Thunder/Postman 客戶端和通過瀏覽器中的應用程序發出的請求)。
我使用 axios,我已經設置了{withCredentials: true}
它不起作用。 我已經使用withAxios
鈎子,但它也不起作用。
服務器
索引.js
...
const app = express()
app.use(cors({
credentials: true,
origin: 'http://localhost:3000',
}));
...
控制器/User.js
...
const loginUser = async(req, res) => {
const body = req.body
const user = await User.findOne({ email: body.email })
if(user) {
const token = generateToken(user)
const userObject = {
userId: user._id,
userEmail: user.email,
userRole: user.role
}
const validPassword = await bcrypt.compare(body.password, user.password)
if(validPassword) {
res.set('Access-Control-Allow-Origin', req.headers.origin);
res.set('Access-Control-Allow-Credentials', 'true');
res.set(
'Access-Control-Expose-Headers',
'date, etag, access-control-allow-origin, access-control-allow-credentials'
)
res.cookie('auth-token', token, {
httpOnly: true,
sameSite: 'strict'
})
res.status(200).json(userObject)
} else {
res.status(400).json({ error: "Invalid password" })
}
} else {
res.status(401).json({ error: "User doesn't exist" })
}
}
...
中間件.js
...
exports.verify = (req, res, next) => {
const token = req.headers.authorization
if(!token) res.status(403).json({ error: "please provide a token" })
else {
jwt.verify(token.split(" ")[1], tokenSecret, (err, value) => {
if(err) res.status(500).json({error: "failed to authenticate token"})
req.user = value.data
next()
})
}
}
...
路由器.js
...
router.get('/bills', middleware.verify, getBills)
router.post('/login', loginUser)
...
客戶
src/components/LoginComponent.js
...
const loginUser = (e) => {
setLoading(true)
e.preventDefault()
let payload = {email: email, password: password}
axios.post('http://localhost:8000/login', payload).then(res => res.status === 200
? (setLoading(false), navigate('/listbills')) : navigate('/register'))
}
...
src/組件/ListBills.js
...
useEffect(() => {
fetch('http://localhost:8000/bills', {
method: 'get',
headers: {'Content-Type': 'application/json'},
credentials: 'include',
})
.then(response => {console.log(response)}).catch(err => console.log(err));
}, [])
...
我也試過:
axios.get('http://localhost:8000/bills',{withCredentials: true})
.then((data) => console.log(data))
.then((result) => console.log(result))
.catch((err) => console.log('[Control Error ] ', err))
}
和
const [{ data, loading, error }, refetch] = useAxios(
'http://localhost:8000/bills',{
withCredentials: true,
headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
}})
控制台日志錯誤:
登錄后,我在“網絡”選項卡中看到了這個:
但是,當我想訪問列表時:
===更新===
所以問題的原因是沒有在請求 header 中傳遞 httpOnly cookie。這是我正在使用的中間件的日志:
token undefined
req headers auth undefined
req headers {
host: 'localhost:8000',
connection: 'keep-alive',
'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
'sec-ch-ua-platform': '"macOS"',
'content-type': 'application/json',
accept: '*/*',
origin: 'http://localhost:3000',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
referer: 'http://localhost:3000/',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9,hr;q=0.8,sr;q=0.7,bs;q=0.6,de;q=0.5,fr;q=0.4,it;q=0.3'
}
令牌是從headers.authorization
中讀取的,但從headers
的日志中它不存在,因此我的請求無法獲得授權。
還是行不通。
在閱讀了CORS
和httpOnly cookies
上的所有內容后,我設法讓它工作了。 首先,我根據 SERVER 上controllers/User.js
中的文檔刪除sameSite
並添加了domain
prop
res.cookie('auth-token', token, {
httpOnly: true,
domain: 'http://localhost:3000'
})
然后我在控制台請求視圖中看到一個黃色的小三角形,它表示域無效。 然后我將domain
更改為origin
並且 cookie 出現在標頭的請求日志中
res.cookie('auth-token', token, {
httpOnly: true,
origin: 'http://localhost:3000',
})
cookie 不在headers
的Authorization
屬性中,而是在cookie
中,所以我不得不更改middleware.js
中的代碼,因為它需要格式bearer xxyyzz
但收到auth-token=xxyyzz
,現在看起來像這樣:
exports.verify = (req, res, next) => {
const token = req.headers.cookie
if(!token) res.status(403).json({ error: "please provide a token" })
else {
jwt.verify(token.split("=")[1], tokenSecret, (err, value) => {
if(err) res.status(500).json({error: "failed to authenticate token"})
req.user = value.data
next()
})
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.