I have a Vue 3 + node express back-end server + firebase.
On my backend server, the middleware:
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" });
}
});
};
The /get routes using the middleware
router.get('/bearer', checkIfAuthenticated, async function(req, res) {
res.send('Bearer test');
})
App using the following path on port 3000:
app.use('/users', userRoute);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
In front-end i want to make the api call for /users/bearer path but i'm still unaunthorized after passing the token in header:
In browser front-end client I'm using this path: 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 router:
{
path: "/users/bearer",
name: "bearer",
component: bearer
}
the config after console log:
console.log(config);
{headers: {…}}
headers: {Authorization: "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjVmOTcxMmEwODc.....
EDIT: In checkIfAuthenticated function my const { authToken } = req; is undefiend
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…