我正在嘗試在 express.js 中創建一個身份驗證中間件,并在 express-unless 包的幫助下打開一些 API,在其中我為所有具有 7 位字母數字字符的 URL 添加了忽略身份驗證的動態路徑。所以,我添加了一個正則運算式[0-9a-zA-Z]{7},但它不起作用。
下面是我寫的javascript代碼
const unprotected = ["api/token", "/", "/api/login", /\/[0-9A-Za-z]{7}/];
module.exports.tokenAuth = jwt({...}).unless({ path: unprotected });
參考的編輯代碼:
require("dotenv").config();
const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
const morganMiddleware = require("./middlewares/morganMiddleware");
const jwt = require("express-jwt");
// setting up middleware
app.use(express.static(path.join(__dirname, "public")));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(morganMiddleware);
const unprotected = [ "/api/login", /\/[0-9A-Za-z]{7}/];
app.use(jwt({ secret: 'shhhhhhared-secret', algorithms: ['HS256']}).unless({ path: unprotected }));
app.get("/:id([a-zA-Z0-9]{7})", (req, res) => {
res.json({
message: "unprotected",
id: req.params.id
})
})
app.post("/api/urlShortener", (req, res) => {
console.log(req.user) //undefined
res.json({
message: "should be protected, but still works without token",
user: req.user
})
})
let PORT = process.env.PORT || 3333;
app.listen(PORT, () => {
console.log("Application listening on port ??????", PORT);
console.log("Server running on \033[0;94mhttp://localhost:" PORT "/ \033[0m");
});
有人可以幫忙嗎?
uj5u.com熱心網友回復:
我使用您的路徑和正則運算式進行了一些測驗,它的作業原理。在這種情況下我沒有使用 express-unless,因為 express-jwt 已經有了這個機制。
const express = require("express")
const jwt = require("express-jwt")
const app = express()
const unprotected = ["api/token", "/", "/api/login", /\/[0-9A-Za-z]{7}/];
app.use(jwt({ secret: 'shhhhhhared-secret', algorithms: ['HS256']}).unless({path: unprotected}))
app.get("/", (req, res) => {
res.json({
message: "unprotected"
})
})
app.get("/:id([a-zA-Z0-9]{7})", (req, res) => {
res.json({
message: "unprotected",
id: req.params.id
})
})
app.listen(8080, () => {
console.log("ok")
})
測驗用例 1:
根路徑本地主機
測驗用例 2:
使用 localhost/250Zip0
測驗用例 3:
使用本地主機/用戶
更新
我收到了來自 TS 的更新,作業正則運算式是:
/^\/[a-zA-Z0-9]{7}$/
示例:https ://regex101.com/r/TdwXNH/1
如果我們不添加起始字串^而只$在末尾添加。無論前綴如何,它都應匹配具有此模式的所有路徑。
/^\/[a-zA-Z0-9]{7}$/
Example 2 : https://regex101.com/r/DmkQGl/1
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/425420.html
標籤:javascript 正则表达式
上一篇:JSDOM:如何訪問嵌套元素
下一篇:從陣列中獲取5個最舊的物件
