[英]Vue 3 still unauthorized after passing the correct token with Bearer
我有一个 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}`)
})
在前端,我想让 api 调用 /users/bearer 路径,但在 header 中传递令牌后我仍然没有授权:
在浏览器前端客户端我使用这个路径: 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
}
控制台日志后的配置:
控制台.log(配置);
{headers: {…}}
headers: {Authorization: "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjVmOTcxMmEwODc.....
编辑:在 checkIfAuthenticated function my const { authToken } = req; 不设防
您可以尝试以不同的方式设置authorization
标头,这里有两种最常见的方法:
带有common
标题:
axios.defaults.headers.common['Authorization'] = <YourToken>;
带interceptor
:
axios.interceptors.request.use(
(config) => {
let token = <getyourToken>
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
在您的代码中,您可以尝试使用 common 将其更改为:
async accesPrivateData() {
const token = await firebase.auth().currentUser.getIdToken();
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
axios.get("http://localhost:3000/users/bearer")
.then(() => {
console.log("Am intrat");
})
.catch(function (error) {
console.log(error);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.