【问题标题】:Vue 3 still unauthorized after passing the correct token with Bearer使用 Bearer 传递正确的令牌后,Vue 3 仍然未经授权
【发布时间】: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


【解决方案1】:

您可以尝试以不同的方式设置 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);
        });
}

【讨论】:

  • 仍然未经授权,我认为我没有以正确的方式集成您的代码。你能编辑我如何正确使用你的机制吗?
  • 我添加了一个带有common 标头的示例。
  • 如果您仍然未经授权而不是检查您的服务器端代码,您的错误可能存在,首先打印出标题并查看您是否在那里收到令牌,除此之外我建议检查您在浏览器上的网络控制台查看正在发出的请求并查找您发送的标头。
  • 是的,在我的后端, const { authToken } = req;未定义
  • 好的,但是你收到令牌了吗?
最近更新 更多