簡體   English   中英

如何在 http 標頭中將 JWT 從服務器傳遞到客戶端

[英]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});
              }
                 
            });

現在這里

  • 如何處理令牌????
  • HEADER 我應該使用什么? 如何?
    
          // 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:

https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/JSON_Web_Token_for_Java_Cheat_Sheet.md#token-storage-on-client-side

感謝 Scopique 的回復。 是的,我確實明白解決這個難題的方法不需要達成共識。 此外,在談論這個時,我遇到了與您相同的 gitHub 問題,哈哈。 我認為,由於 web 安全受到威脅,因此必須在 RFC 標准的描述中包含安全方法。

由於我目前不關心前端方面,所以我沒有考慮如何存儲我的令牌。 但是,我勾勒出了這個簡略的圖表。 (注意:我並沒有規定這是好的做法。)。 這是我目前找到的最好的在此處輸入圖像描述

我只是希望做那樣的事情不是壞事。 至少是第一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM