[英]How do I pass the JWT from the server to the client in a an http-header
無論我多么努力地尋找答案,我都不滿意。 我到處都能找到關於如何將 JWT 令牌從客戶端傳遞到服務器的解釋,以及最安全的方法。 然而,這讓我有點不爽。 我想通過 HTTP header 將客戶的 JWT 令牌發送給后者,但哪一個? 據我了解,這是最安全的方式,而不是使用 cookie。
假設用戶已經在我的數據庫中注冊。 他向服務器提交了登錄表單,我檢索了憑據,並從中生成了一個 JWT。現在我正在使用 express,如何將 JWT 發送到 header 中的客戶?
我在我的案例中使用 express
app.post("/login", async (inReq, inRes) => {
//Loadin the user's database
usersDB.loadDatabase((err)=>{
if (err) {console.log("Error while loading database: usersDB")};
});
// Our login logic starts here
//We get the user's data
const { username, password } = inReq.body;
//We validate user input in some way.
if(username.length < 4 || password.length < 8)
return inRes.status(400).send('Bad data');
//and then we try to
try {
//Check if the user exists in our database
const foundUser = await findUser(usersDB,{"username":username});
//Compare the two passwords (the one found in the DB and the one sent by our client)
if (foundUser && (await bcrypt.compare(password, foundUser.password))) {
//If evrything's fine we create token
const token = await jwt.sign(
{ user_id: foundUser._id, username },
process.env.TOKEN_KEY,
{
expiresIn: "40s",
},
function(err, intoken) {
if(err) {
console.log(err);
return inRes.status(500).json({current_view: 'error', data: err});
}
});
現在這里
// make a response to the user (successful login)
return inRes.status(200).json(current_view: 'home', data: user);
}
//If the user is not valid we send an error
return inRes.status(401).json(current_view: 'login', data: 'wrong-credentials');
}
//We catch and log any error
catch (err) {
console.log(err);
}
// Our register logic ends here
});
我現在也在同一條船上; 正如您現在可能已經發現的那樣,對於如何將 JWT 發送給客戶端還沒有權威的共識。 到目前為止我看到的唯一經驗法則來自此鏈接:
https://github.com/dwyl/hapi-auth-jwt2/issues/82#issuecomment-129873082
將 JWT 令牌放在授權 header 中使我們能夠靈活地在 web 應用程序中發送實際響應。 對於僅限 REST 的應用程序/API,您可以自由發送 JWT 作為響應正文或 cookie。 重要的是客戶端如何存儲 JWT 並將其發送回服務器,這是在授權 header(或 Cookie 或 URL Token,如果您願意)中完成的
至於這個“野外”存在的問題,我還沒有看到服務器向客戶端發送授權 header 的示例,但規范中沒有任何內容表明這是一種反模式。 請參閱: http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html
使用 Express,我一直在測試通過授權 header 發送 JWT:
inRes.set('Authorization', `Bearer ${myJWT}`);
在設置 inRes.status 之前執行此操作。
在客戶端,事情似乎更簡單一些。 我讀過的所有內容都說不要將 JWT 存儲在 localStorage 中(如果這甚至是您的選擇),因為沒有過期屬性。 Cookies 只是稍微好一點,因為它們可以設置為按日期或 session 過期,但有一個額外的功能,即它們會隨着未來的請求被發送回服務器。 在這一點上,sessionStorage 是一種潛力,因為它有一個嚴格而快速的有效期,因為它們只會持續到瀏覽器關閉。
您可以查看下面鏈接的建議(雖然示例特定於 Java,但更多的是通用解釋)以了解如何在客戶端上存儲 JWT:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.