【发布时间】:2024-01-14 21:42:01
【问题描述】:
我有一个 Vue 3 + node express 后端服务器 + firebase。 在我的后端服务器上,中间件:
const getAuthToken = (req, _, next) => {
if (
req.headers.authorization &&
req.headers.authorization.split(" ")[0] === "Bearer"
) {
req.authToken = req.headers.authorization.split(" ")[1];
} else {
req.authToken = null;
}
next();
};
const checkIfAuthenticated = (req, res, next) => {
getAuthToken(req, res, async() => {
try {
const { authToken } = req;
const userInfo = await admin.auth().verifyIdToken(authToken);
req.authId = userInfo.uid;
return next();
} catch (e) {
return res
.status(401)
.send({ error: "You are not authorized to make this request" });
}
});
};
使用中间件的 /get 路由
router.get('/bearer', checkIfAuthenticated, async function(req, res) {
res.send('Bearer test');
})
应用程序在端口 3000 上使用以下路径:
app.use('/users', userRoute);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
在前端我想对 /users/bearer 路径进行 api 调用,但在标头中传递令牌后我仍然没有授权:
在浏览器前端客户端我使用这个路径:http://localhost:8080/users/bearer
async accesPrivateData() {
const token = await firebase.auth().currentUser.getIdToken();
let config = {
headers: {
Authorization: `Bearer ${token}`
}
};
axios.get("http://localhost:3000/users/bearer",config)
.then(() => {
console.log("Am intrat");
})
.catch(function (error) {
console.log(error);
});
}
**I tried to console log the token and it's there!**
Index.js Vue 路由器:
{
path: "/users/bearer",
name: "bearer",
component: bearer
}
控制台日志后的配置:
console.log(config);
{headers: {…}}
headers: {Authorization: "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjVmOTcxMmEwODc.....
编辑:在 checkIfAuthenticated 函数中我的 const { authToken } = req;是无敌的
【问题讨论】:
-
你检查网络请求了吗?令牌是否附加在标头中?
-
检查我编辑的答案
标签: javascript node.js express vue.js token