使用Express验证JWT令牌。

huangapple go评论94阅读模式
英文:

Validate a jwt token with express

问题

I've been getting a lot of errors saying

  1. POST http://localhost:4000/api/payment/create-checkout-session 403 (Forbidden)
  2. AxiosError {message: 'Request failed with status code 403', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {...}, request: XMLHttpRequest, …}
  3. code
  4. :
  5. "ERR_BAD_REQUEST"
  6. config
  7. :
  8. "Request failed with status code 403"
  9. name
  10. :
  11. "AxiosError"
  12. request
  13. {data: 'A token is required', status: 403, statusText: 'Forbidden', headers: Axios

I think it has something to do with my token validation, this is the file for token validation

  1. const verifyToken = (req, res, next) => {
  2. const token = req.body.token || req.query.token || req.headers['Authorization'];
  3. console.log("Token: ", token);
  4. if (!token) {
  5. return res.status(403).send("A token is required");
  6. }
  7. try {
  8. const decoded = jwt.verify(token, process.env.JWT_SECRET);
  9. req.user = decoded;
  10. next();
  11. } catch (err) {
  12. return res.status(401).send("Invalid token, this is the error message:" + err);
  13. }
  14. };
  15. module.exports = verifyToken;

This is the file that is making the axios post request

  1. const token = Cookies.get("token");
  2. console.log("token from catalog " + token)
  3. const checkout = () => {
  4. axios({
  5. method: "post",
  6. url: "http://localhost:4000/api/payment/create-checkout-session",
  7. headers: {
  8. 'Content-Type': 'application/json',
  9. 'Accept': 'application/json',
  10. "Authorization": "Bearer " + token,
  11. }
  12. }).then(response => {
  13. if (response.ok) return response.json();
  14. return response.json().then(json => Promise.reject(json))
  15. })
  16. .then(({ url }) => {
  17. window.location = url;
  18. })
  19. .catch(error => {
  20. console.log(error)
  21. })
  22. }

This is the Express file that the axios is posting to

  1. require('./middleware')
  2. router.post("/create-checkout-session", async (req, res) => {
  3. const { items } = req.body;
  4. // Create a PaymentIntent with the order amount and currency
  5. const paymentIntent = await stripe.paymentIntents.create({
  6. amount: calculateOrderAmount(items),
  7. currency: "usd",
  8. automatic_payment_methods: {
  9. enabled: true,
  10. },
  11. });
  12. res.send({
  13. clientSecret: paymentIntent.client_secret,
  14. });
  15. })
  16. module.exports = router;

Is there a better way to validate a token, or am I missing a header or something in my axios request?

英文:

Ive been getting a lot of errors saying

  1. POST http://localhost:4000/api/payment/create-checkout-session 403 (Forbidden)
  2. AxiosError {message: 'Request failed with status code 403', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
  3. code
  4. :
  5. "ERR_BAD_REQUEST"
  6. config
  7. :
  8. "Request failed with status code 403"
  9. name
  10. :
  11. "AxiosError"
  12. request
  13. {data: 'A token is required', status: 403, statusText: 'Forbidden', headers: Axios

I think it has something to do with my token validation, this is the file for token validation

  1. const verifyToken = (req, res, next) => {
  2. const token = req.body.token || req.query.token || req.headers['Authorization'];
  3. console.log("Token: ", token);
  4. if (!token) {
  5. return res.status(403).send("A token is required");
  6. }
  7. try {
  8. const decoded = jwt.verify(token, process.env.JWT_SECRET);
  9. req.user = decoded;
  10. next();
  11. } catch (err) {
  12. return res.status(401).send("Invalid token, this is the error message:" + err);
  13. }
  14. };
  15. module.exports = verifyToken;

this is the file that is making the axios post request

  1. const token = Cookies.get("token");
  2. console.log("token from catalog " + token)
  3. const checkout = () => {
  4. axios({
  5. method: "post",
  6. url: "http://localhost:4000/api/payment/create-checkout-session",
  7. headers: {
  8. 'Content-Type': 'application/json',
  9. 'Accept': 'application/json',
  10. "Authorization": "Bearer " + token,
  11. }
  12. }).then(response => {
  13. if (response.ok) return response.json();
  14. return response.json().then(json => Promise.reject(json))
  15. })
  16. .then(({ url }) => {
  17. window.location = url;
  18. })
  19. .catch(error => {
  20. console.log(error)
  21. })
  22. }

this is the express file that the axios is posting too

  1. require('./middleware')
  2. router.post("/create-checkout-session", async (req, res) => {
  3. const { items } = req.body;
  4. // Create a PaymentIntent with the order amount and currency
  5. const paymentIntent = await stripe.paymentIntents.create({
  6. amount: calculateOrderAmount(items),
  7. currency: "usd",
  8. automatic_payment_methods: {
  9. enabled: true,
  10. },
  11. });
  12. res.send({
  13. clientSecret: paymentIntent.client_secret,
  14. });
  15. })
  16. module.exports = router;

is there a better way to validate a toke, or am I missing a header or something in my axios request?

答案1

得分: 1

我认为你的验证是正确的,不需要深入研究你的代码。

你之所以得到403错误是因为没有Authorization头部信息。我假设你正在使用express。尽管你指定了头部是Authorization,但在express中要访问请求头部,你需要查找req.headers.authorization,其中a是小写。

我运行了一个简单的应用程序:

  1. import express from "express";
  2. const app = express();
  3. app.listen(3000, () => {
  4. console.log("hi there 3000");
  5. });
  6. app.post("/auth", (req, res) => {
  7. console.log(req.headers);
  8. res.status(200).send(req.headers);
  9. });

然后使用curl进行了以下操作:➜ curl --header "Authorization: Bearer something" -I -X POST http://localhost:3000/auth

req.headers的输出如下:

  1. {
  2. host: 'localhost:3000',
  3. 'user-agent': 'curl/7.79.1',
  4. accept: '*/*',
  5. authorization: 'Bearer something'
  6. }

如果有帮助,请告诉我。

英文:

Without digging too much into your code I think that your validation is fine.

You are getting the 403 because there is no Authorization header. I am going to assume that you are using express. Even though you specified that the header is Authorization with a capital A, in express to access that request header you have to look for req.headers.authorization with a lower-cased a.

I ran a simple app:

  1. import express from "express";
  2. const app = express();
  3. app.listen(3000, () => {
  4. console.log("hi there 3000");
  5. });
  6. app.post("/auth", (req, res) => {
  7. console.log(req.headers);
  8. res.status(200).send(req.headers);
  9. });

Then curled the following: ➜ curl --header "Authorization: Bearer something" -I -X POST http://localhost:3000/auth

The req.headers is as follows:

  1. {
  2. host: 'localhost:3000',
  3. 'user-agent': 'curl/7.79.1',
  4. accept: '*/*',
  5. authorization: 'Bearer something'
  6. }

Let me know if this helps.

huangapple
  • 本文由 发表于 2023年6月16日 06:07:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76485807.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定