簡體   English   中英

僅使用 express basic auth 檢查授權

[英]Check authorization with express basic auth only

我正在嘗試檢查是否有人在我的鏈接中為名為'/protected'的特定路徑輸入了授權的用戶名和密碼,例如:admin:admin@localhost:8080/protected

如果這個人輸入了這個,那么他會到達一個頁面,上面寫着“歡迎授權”

如果此人沒有像這樣輸入鏈接,而只是: localhost:8080/protected 他將收到一條消息“未授權”以及錯誤 401

這是我想出的代碼,但只有您獲得授權才會收到一條消息,否則您什么也收不到。

router.get('/protected', basicAuth({
        users: {'admin':'admin'}
    }),(req,res)=>{
    res.send('Welcome, authenticated client');
});

看起來您正在使用express-basic-auth package,默認情況下,當授權被拒絕時不發送響應正文。

根據文檔,要向授權失敗的請求添加響應正文,您需要將unauthorizedResponse響應屬性添加到您傳遞給basicAuth中間件的 object 中。

要添加通用消息,它可以像字符串一樣簡單。

router.get('/protected', basicAuth({
        users: {'admin':'admin'},
        unauthorizedResponse: 'not authorized'
    }),(req,res)=>{
    res.send('Welcome, authenticated client');
});

要添加動態消息,您可以使用 function(它將通過第一個參數訪問請求 object):

router.get('/protected', basicAuth({
        users: {'admin':'admin'},
        unauthorizedResponse: getUnauthorizedResponse
    }),(req,res)=>{
    res.send('Welcome, authenticated client');
});

function getUnauthorizedResponse(req) {
    const { user } = req.auth?.user ?? {}
    return user ? `invalid credentials for user '${user}'` : 'no credentials provided';
}

暫無
暫無

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

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