Created
May 25, 2021 07:36
-
-
Save Yapcheekian/7bdabeb25f326092d59e7e44dffd913c to your computer and use it in GitHub Desktop.
Basic auth simple implementation in js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require("express"); | |
const app = express(); | |
const PORT = process.env.PORT || 5000; | |
app.get("/", (req, res) => { | |
res.send("Hello World!"); | |
}); | |
const authMiddleware = (req, res, next) => { | |
const auth = req.headers.authorization; // 嘗試抓出 Authorization: Basic c3R1ZGVudDo5NTI3 | |
let authorized = false; | |
if (auth && auth.includes("Basic")){ | |
const token = auth.split("Basic ")[1]; // 取出 c3R1ZGVudDo5NTI3 | |
const usernamePassword = Buffer.from(token, 'base64').toString() // 解碼成 帳號:密碼 | |
console.log(usernamePassword) // 印出來看一下結果 | |
if (usernamePassword === 'student:9527'){ | |
authorized = true; | |
} | |
} | |
// 驗證失敗就直接回傳 401 未授權 | |
if (!authorized) { | |
res.setHeader("WWW-Authenticate", "Basic realm='view files'"); | |
res.status(401).send("請先登入才可以看!"); | |
return | |
} | |
next(); | |
}; | |
// 存取/calculus時,會先經過 authMiddleware 檢查,通過才會回傳微積分講義 | |
app.get("/calculus", authMiddleware, (req, res) => { | |
res.send(` | |
<h1>微積分講義</h1> | |
<ul> | |
<li>Chapter 1.ppt</li> | |
<li>Chapter 2.ppt</li> | |
</ul> | |
`); | |
}); | |
// 同 /calculus,存取時也會先經過驗證檢查 | |
app.get("/linear_algebra", authMiddleware, (req, res) => { | |
res.send(` | |
<h1>線性代數講義</h1> | |
<ul> | |
<li>LA Chapter 1.ppt</li> | |
<li>LA Chapter 2.ppt</li> | |
</ul> | |
`); | |
}); | |
app.listen(PORT, () => { | |
console.log(`Listening on port ${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment