簡體   English   中英

如何將 jwt 令牌從 web 瀏覽器上的本地存儲傳輸到服務器后端?

[英]How do I transfer a jwt token from local storage on the web browser to the server backend?

我目前正在設計一個簡單的網站,用戶可以在其中以普通用戶或管理員身份登錄。 Right now I am coding out the portion for when the user wants to go to an admin only web page, and the server will retrieve the jwt token stored in the local storage on the web browser to validate it.

Web瀏覽器的本地存儲

這就是本地存儲的樣子

這是檢索 jwt 令牌的代碼

var verifyFn = {
verifyToken: function (req, res, next) {
    const authHeader = localStorage.getItem("jwt_token");
    console.log("THIS IS THE HEADER")
    console.log(authHeader)
    
    if (authHeader === null || authHeader === undefined ){
    return res.status(401).send({ message: 'not authenticated BEARER TOKEN ISSUE' });
    }

    const token = authHeader
    console.log("NEW TOKEN")
    console.log(token)
    jwt.verify(token, config.jwt.secret, { algorithms: ['HS256'] }, (err, decoded) => {
        if (err) return res.status(401).send({ message: 'not authenticated' });
        req.decodedToken = decoded;
        console.log("DECODED TOKEN: " + req.decodedToken)
        next();
    });
}

但是,每當我嘗試運行服務器並瀏覽到管理頁面時,都會出現錯誤提示“未定義本地存儲”。 因此,我不確定如何將 jwt_token 從 web 瀏覽器檢索到服務器后端。

服務器無法訪問瀏覽器的localStorage object,因為它只能從客戶端訪問,並且不存在於服務器上下文中。

通常所做的是在Authorization header 中發送令牌。 看起來您正在使用Node ,因此請考慮使用客戶端上的 fetch API 的以下示例請求:

 const jwtToken = localStorage.getItem('jwt_token') fetch('your-api-url', { method: 'request method here', headers: { Authorization: `Bearer ${jwtToken}` }, body: JSON.stringify(your request body here) }).then(response =>...)

在服務器中,您可以通過查看響應標頭來獲取 JWT 令牌,如下所示:

 var verifyFn = { verifyToken: function (req, res, next) { let authHeader = req.headers['Authorization'] // the auth header will have Bearer prepended, so remove it authHeader = authHeader.replace('Bearer ', '') console.log("THIS IS THE HEADER") console.log(authHeader) if (authHeader === null || authHeader === undefined ){ return res.status(401).send({ message: 'not authenticated BEARER TOKEN ISSUE' }); } const token = authHeader console.log("NEW TOKEN") console.log(token) jwt.verify(token, config.jwt.secret, { algorithms: ['HS256'] }, (err, decoded) => { if (err) return res.status(401).send({ message: 'not authenticated' }); req.decodedToken = decoded; console.log("DECODED TOKEN: " + req.decodedToken) next(); }); }

暫無
暫無

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

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