Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.0k views
in Technique[技术] by (71.8m points)

javascript - Vue 3 still unauthorized after passing the correct token with Bearer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try setting the authorization headers in different ways, here the 2 most common ways to do it:

with common headers:

axios.defaults.headers.common['Authorization'] = <YourToken>;

with interceptor:

axios.interceptors.request.use(
(config) => {
    let token = <getyourToken>
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
},

(error) => {
    return Promise.reject(error);
}

);

In your code you could try with common by change it to:

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);
        });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...