Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

authentication - JWT test works on Rest Client, but it doesn't work on Postman

I am learning JWT for a project that I must submit. I tested something using the VS Code plugin REST Client and it worked, but when I try the same using Postman (in the project they ask me to use Postman) it doesn't work.

My code is the following:

require("dotenv").config();
const express = require("express");
const app = express();
const jwt = require("jsonwebtoken");

const posts = [
{
username: "John",
title: "Post 1",
},
{
username: "Joe",
title: "Post 2",
},
];

app.use(express.json());
app.get("/posts", authToken, (req, res) => {
res.json(posts.filter((post) => post.username === req.user.name));
});

app.post("/login", (req, res) => {
const username = req.body.username;
const user = { name: username };
const tokenAccess = jwt.sign(user, process.env.TOKEN);
res.json({ tokenAccess: tokenAccess });
});

app.listen(4000);

function authToken(req, res, next) {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, process.env.TOKEN, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}

In the .env file, I wrote:

TOKEN='71e30f718719170cf4a727a9'
TOKEN_REFRESH='b5010378bf2bd96c3000e48e'

Using the REST Client plugin, I created a test.rest file:

GET http://localhost:4000/postsAuthorization: Bearer XXXX

###

POST http://localhost:4000/login

Content-Type: application/json

{"username": "John"}

To try it, I send the POST request and I receive the token, which I put instead the XXXX space. Then I send the GET request and it works.

But as I said, when I try the same on Postman, it doesn't work. I do receive the token when I send the POST request, but when I use it to send the GET request, I receive an empty array. Could you please give me the instructions to do it well? Thanks a lot!

question from:https://stackoverflow.com/questions/65928632/jwt-test-works-on-rest-client-but-it-doesnt-work-on-postman

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

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...